可能重复:
Finding an enum value by its Description Attribute得到Description属性枚举
我有后者从一个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));
如果在字符串前添加“this”关键字... public static T GetValueFromDescription(this string description)...它成为一种扩展方法,你可以使用如下语法:var x =“Giant Panda”.GetValueFromDescription (); –
2012-02-29 18:16:10
我喜欢这种方法。适用于我,并且非常优雅。 – beaudetious 2012-09-25 17:58:22