可能重复:
通过其描述属性查找枚举值
我有一个通用的扩展方法,它Description从以下方式获取属性Enum:
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;
}
Run Code Online (Sandbox Code Playgroud)
所以我可以......
string myAnimal = Animal.GiantPanda.GetDescription(); // = "Giant Panda"
Run Code Online (Sandbox Code Playgroud)
现在,我正试图在另一个方向上找出等效函数,比如......
Animal a = (Animal)Enum.GetValueFromDescription("Giant Panda", typeof(Animal));
Run Code Online (Sandbox Code Playgroud)