如何在C#中将字符串分配给枚举而不是整数值?

Rik*_*ika 6 c# enums

我正在尝试为枚举分配一个字符串.像下面的例子:

    enum MyEnum
    {
        frist = "First Value",
        second = "Second Value",
        third = "Third Value"
    }
Run Code Online (Sandbox Code Playgroud)

所以我可以在我的代码中有这样的东西:

MyEnum enumVar = MyEnum.first;
...
string enumValue = EnumVar.ToString();//returns "First Value"
Run Code Online (Sandbox Code Playgroud)

以传统的方式,当我创建一个枚举时,ToString()将返回枚举名称而不是其值.所以这是不可取的,因为我正在寻找一种方法来分配一个字符串值,然后从枚举中获取该字符串值.

Hab*_*bib 20

您可以在枚举中添加Description属性.

enum MyEnum
    {
        [Description("First Value")]
        frist, 
        [Description("Second Value")]
        second, 
        [Description("Third Value")]
        third,
    }
Run Code Online (Sandbox Code Playgroud)

然后有一个方法来返回您的描述.

public static string GetEnumDescription(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());

            DescriptionAttribute[] attributes =
                (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attributes != null && attributes.Length > 0)
                return attributes[0].Description;
            else
                return value.ToString();
        }
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

   MyEnum enumVar = MyEnum.frist;
   string value = GetEnumDescription(enumVar);
Run Code Online (Sandbox Code Playgroud)

价值将持有"第一价值"

您可能会看到:在C#中将字符串与枚举关联


Run*_* FS 6

你不能枚举的值总是一个整数

您最接近的是具有一组静态属性的静态类

static class MyValues
{
    public static readonly string First = "First Value";
    public static readonly string Second = "Second Value";
    public static readonly string Third = "Third Value";
}
Run Code Online (Sandbox Code Playgroud)

  • @Dervall我没有写int而是整数(不是C#中的类型,而是英文单词) (2认同)