Conversion between C#_ enumeration and string

Table of contents

enum to string

string interpolation

ToString()

string to enum

Enum.Parse()

Enum.TryParse()


    enum MyEnum
    {
        Enum0,
        Enum1,
        Enum2
    }

    enum OtherEnum
    {
        OtherEnum0,
        OtherEnum1,
        OtherEnum2
    }

enum to string

  • string interpolation

    Console.WriteLine($"{MyEnum.Enum0}");

    //输出:Enum0

  • ToString()

    Console.WriteLine(MyEnum.Enum0.ToString());

    //输出:Enum0

string to enum

  • Enum.Parse()

    OtherEnum otherEnum = (OtherEnum) Enum.Parse(typeof(MyEnum), "Enum0");

    Console.WriteLine(otherEnum);

    //输出:OtherEnum0

The first parameter of *Enum.Parse() is the type, specified with typeof().

  • Enum.TryParse<T>()

    OtherEnum otherEnum;

    if (Enum.TryParse("OtherEnum0", out otherEnum))
    {
        Console.WriteLine(otherEnum.ToString());
    }

    //输出:OtherEnum0

Guess you like

Origin blog.csdn.net/ashmoc/article/details/125232953