如何在C#中为字符串分配字符串而不是整数值?

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

enum MyEnum { frist = "First Value", second = "Second Value", third = "Third Value" } 

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

 MyEnum enumVar = MyEnum.first; ... string enumValue = EnumVar.ToString();//returns "First Value" 

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

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

 enum MyEnum { [Description("First Value")] frist, [Description("Second Value")] second, [Description("Third Value")] third, } 

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

 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(); } 

然后你可以这样做:

  MyEnum enumVar = MyEnum.frist; string value = GetEnumDescription(enumVar); 

价值将持有“第一价值”

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

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

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

 static class MyValues { public static readonly string First = "First Value"; public static readonly string Second = "Second Value"; public static readonly string Third = "Third Value"; } 

你不能这样做。 enum基于整数,而不是字符串。

枚举的已批准类型是byte,sbyte,short,ushort,int,uint,long或ulong。 所以像字符串一样,你唯一能做的就是

枚举MyEnum {第一,第二,第三}

MyEnum.first.ToString();

或者喜欢使用reflection并使用描述作为枚举中字段的属性。

 enum MyEnum { FirstValue, //Default Value will be 0 SecondValue, // 1 ThirdValue // 2 } string str1 = Enum.GetName(typeof(MyEnum), 0); //will return FirstValue string str2 = Enum.GetName(typeof(MyEnum), MyEnum.SecondValue); //SecondValue 

如果你需要一个像空格一样的完整字符串,你需要添加描述方法。 另外我建议只创建一个查找字典。

  string value = MyLookupTable.GetValue(1); // First Value value = MyLookupTable.GetValue(2); // Second Value value = MyLookupTable.GetValue(3); // Third Value class MyLookupTable { private static Dictionary lookupValue = null; private MyLookupTable() {} public static string GetValue(int key) { if (lookupValue == null || lookupValue.Count == 0) AddValues(); if (lookupValue.ContainsKey(key)) return lookupValue[key]; else return string.Empty; // throw exception } private static void AddValues() { if (lookupValue == null) { lookupValue = new Dictionary(); lookupValue.Add(1, "First Value"); lookupValue.Add(2, "Second Value"); lookupValue.Add(3, "Third Value"); } } }