枚举带有字符串值并通过值查找枚举 [英] Enums with string values and finding enum by value
问题描述
public enum Fruit
{
Apple =A
香蕉=B
Cherry =C
}
更新:就像一个查找表,不同之处在于值是string而不是int。我正在填充一个业务对象,通过读取数据库中的值,我想使用一个具有固定值的对象属性而不是字符串的类型。
我使用枚举中的描述属性解决了问题。解决方案如下。我使用扩展方法来获取描述。获取描述的代码取自此链接 http://blog.spontaneouspublicity.com/post/2008/01/17/Associating-Strings-with-enums-in-C.aspx 。感谢您的答复。
public enum Fruit
{
[Description(Apple)]
A,
[描述(香蕉)]
B,
[描述(樱桃)]
C
}
public static class Util
{
public static T StringToEnum< T>(string name)
{
return(T)Enum.Parse(typeof(T) );
}
public static string ToDescriptionString(此枚举值)
{
FieldInfo fi = value.GetType()。GetField(value.ToString());
DescriptionAttribute [] attributes =
(DescriptionAttribute [])fi.GetCustomAttributes(
typeof(DescriptionAttribute),
false);
if(attributes!= null&&
attributes.Length> 0)
返回属性[0] .Description;
else
返回值.ToString();
}
}
I want to have an enum like the following and then have a method something like Util.FindFruitByValue("A") which returns the enum Apple. this is because the abbreviations are stored in database and I need to convert them to appropriate enums after reading from db. is this possible OR do I need to create a separate class for it? Please let me know. thanks in advance.
public enum Fruit
{
Apple = "A"
Banana = "B"
Cherry = "C"
}
Update: this is like a lookup table, but the difference is the value is string instead of an int. I am populating a business object, by reading the values from database and I would like to use a type with fixed values for the object property instead of string.
I solved the problem by using the Description attribute on the enum. the solution is as follows. I use the extension method to get the description. the code to get the description is taken from this link http://blog.spontaneouspublicity.com/post/2008/01/17/Associating-Strings-with-enums-in-C.aspx. thanks for your replies.
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();
}
}
这篇关于枚举带有字符串值并通过值查找枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!