从描述属性获取Enum我有一个泛型扩展方法,它获取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;}所以我可以.。string myAnimal = Animal.GiantPanda.GetDescription(); // = "Giant Panda"现在,我试着在另一个方向上计算出等价的函数,就像.Animal a = (Animal)Enum.GetValueFromDescription("Giant Panda", typeof(Animal));
3 回答
拉风的咖菲猫
TA贡献1995条经验 获得超2个赞
public static class Utility{ public static string GetDescriptionFromEnumValue(Enum value) { DescriptionAttribute attribute = value.GetType() .GetField(value.ToString()) .GetCustomAttributes(typeof (DescriptionAttribute), false) .SingleOrDefault() as DescriptionAttribute; return attribute == null ? value.ToString() : attribute.Description; } public static T GetEnumValueFromDescription<T>(string description) { var type = typeof(T); if (!type.IsEnum) throw new ArgumentException(); FieldInfo[] fields = type.GetFields(); var field = fields .SelectMany(f => f.GetCustomAttributes( typeof(DescriptionAttribute), false), ( f, a) => new { Field = f, Att = a }) .Where(a => ((DescriptionAttribute)a.Att) .Description == description).SingleOrDefault(); return field == null ? default(T) : (T)field.Field.GetRawConstantValue(); }}
var result1 = Utility.GetDescriptionFromEnumValue( Animal.GiantPanda);var result2 = Utility.GetEnumValueFromDescription<Animal>( "Lesser Spotted Anteater");
- 3 回答
- 0 关注
- 609 浏览
添加回答
举报
0/150
提交
取消