可能重复:通过其描述属性查找枚举值
我有一个通用的扩展方法,从 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));
6 回答
你不能扩展
Enum
,因为它必须自己创建一个静态方法才能做到这一点;当与现有方法结合使用时,以下内容应该有效GetDescription
:它的用法将是这样的:
除非您有Web服务,否则解决方案很有效 .
您需要执行以下操作,因为描述属性不可序列化 .
您需要迭代Animal中的所有枚举值,并返回与您需要的描述匹配的值 .
应该非常简单,它只是你以前的方法的反面;
用法:
用法:
而不是扩展方法,只需尝试几个静态方法
并在这里使用