1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Linq; 5 6 namespace EnumHelper 7 { 8 /// <summary> 9 /// 枚举帮助类 10 /// 1、获取枚举的描述文本 11 /// 2、获取枚举名和描述信息的列表 12 /// </summary> 13 public static class EnumHelper 14 { 15 /// <summary> 16 /// 获取枚举值的描述文本 17 /// </summary> 18 /// <param name="e">枚举值</param> 19 /// <returns></returns> 20 public static string Description(this System.Enum e) 21 { 22 Type enumType = e.GetType(); 23 var name = Enum.GetName(enumType, e); 24 string des = GetDescription(enumType, name); 25 return des; 26 } 27 28 /// <summary> 29 /// 获取枚举名和描述信息的列表 30 /// </summary> 31 /// <typeparam name="T">枚举类型</typeparam> 32 /// <param name="EnumType">类型</param> 33 /// <returns>枚举名和描述信息键值对</returns> 34 public static Dictionary<T, string> GetEnumAndDescription<T>(this Type EnumType) where T : struct 35 { 36 if (!EnumType.IsEnum) 37 throw new ArgumentException("GetEnumValues: Type '" + EnumType.Name + "'不是枚举类型"); 38 39 Dictionary<T, string> dic = new Dictionary<T, string>(); 40 foreach (var item in Enum.GetNames(EnumType)) 41 { 42 var _enum = (T)Enum.Parse(EnumType, item); 43 var des = GetDescription(EnumType, item); 44 dic.Add(_enum, des); 45 } 46 return dic; 47 } 48 49 /// <summary> 50 /// 获取枚举名的描述文本 51 /// </summary> 52 /// <param name="enumType">类型</param> 53 /// <param name="name">枚举名</param> 54 /// <returns>描述文本</returns> 55 private static string GetDescription(Type enumType, string name) 56 { 57 string des = string.Empty; 58 var fieldInfo = enumType.GetFields().FirstOrDefault(a => a.Name == name); 59 object[] obj = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); 60 if (obj.Length > 0) 61 { 62 des = ((DescriptionAttribute)obj[0]).Description; 63 } 64 return des; 65 } 66 } 67 }