我目前正在实现基于 this suggestion 的字符串和枚举的关联.也就是说,我有一个与每个枚举元素关联的 Description
属性。在那个页面上还有一个函数,它根据给定的枚举返回描述的字符串。我现在想实现的是反向函数,即给定一个输入字符串查找具有相应描述的枚举(如果存在),否则返回 null。
我试过 (T) Enum.Parse(typeof(T), "teststring")
但它抛出异常。
最佳答案
你必须自己编写反向方法。常用的 Parse() 方法显然不知道您的描述属性。
像这样的东西应该可以工作:
public static T GetEnumValueFromDescription<T>(string description)
{
MemberInfo[] fis = typeof(T).GetFields();
foreach (var fi in fis)
{
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0 && attributes[0].Description == description)
return (T)Enum.Parse(typeof(T), fi.Name);
}
throw new Exception("Not found");
}
不过,如果找不到枚举值,您会想找到比抛出异常更好的方法。 :)
关于c# - 带描述的枚举字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4249632/