從描述屬性獲取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"現(xiàn)在,我試著在另一個方向上計算出等價的函數(shù),就像.Animal a = (Animal)Enum.GetValueFromDescription("Giant Panda", typeof(Animal));
3 回答

拉風的咖菲貓
TA貢獻1995條經(jīng)驗 獲得超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 關注
- 639 瀏覽
添加回答
舉報
0/150
提交
取消