< p > 可能的重复: < br > 通过描述属性查找枚举值 < / p >
我有一个泛型扩展方法,它从Enum
中获取Description
属性:
enum Animal
{
[Description("")]
NotSet = 0,
[Description("Giant Panda")]
GiantPanda = 1,
[Description("Lesser Spotted Anteater")]
LesserSpottedAnteater = 2
}
public static string GetDescription(this Enum value)
{
FieldInfo field = value.GetType().GetField(value.ToString());
DescriptionAttribute attribute
= Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))
as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
所以我可以做…
string myAnimal = Animal.GiantPanda.GetDescription(); // = "Giant Panda"
现在,我试着在另一个方向上算出等效函数,就像……
Animal a = (Animal)Enum.GetValueFromDescription("Giant Panda", typeof(Animal));