我希望有一个类似下面的枚举,然后有一个类似于Util.FindFruitByValue("A")的方法返回枚举Apple.这是因为缩写存储在数据库中,我需要在从db读取后将它们转换为适当的枚举.这是可能的还是我需要为它创建一个单独的类?请告诉我.提前致谢.
public enum Fruit
{
Apple = "A"
Banana = "B"
Cherry = "C"
}
Run Code Online (Sandbox Code Playgroud)
更新:这就像一个查找表,但区别在于值是字符串而不是int.我通过从数据库中读取值来填充业务对象,我想使用具有固定值的类型而不是字符串.
RKP*_*RKP 21
我通过使用枚举上的Description属性解决了这个问题.解决方案如下.我使用扩展方法来获取描述.获取描述的代码来自此链接http://blog.spontaneouspublicity.com/post/2008/01/17/Associating-Strings-with-enums-in-C.aspx.谢谢你的回复.
public enum Fruit
{
[Description("Apple")]
A,
[Description("Banana")]
B,
[Description("Cherry")]
C
}
public static class Util
{
public static T StringToEnum<T>(string name)
{
return (T)Enum.Parse(typeof(T), name);
}
public static string ToDescriptionString(this 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)
Guf*_*ffa 12
您可以将值放在a中Dictionary以有效地查找它们:
Dictionary<string, Fruit> fruitValues = new Dictionary<string, Fruit>();
fruitValues.Add("A", Fruit.Apple);
fruitValues.Add("B", Fruit.Banana);
fruitValues.Add("C", Fruit.Cherry);
Run Code Online (Sandbox Code Playgroud)
抬头:
string dataName = "A";
Fruit f = fruitValues[dataName];
Run Code Online (Sandbox Code Playgroud)
如果该值可能不存在:
string dataName = "A";
Fruit f;
if (fruitValues.TryGetValue(dataName, out f)) {
// got the value
} else {
// there is no value for that string
}
Run Code Online (Sandbox Code Playgroud)