枚举工具
1 public static partial class Extensions 2 { 3 #region 枚举成员转成dictionary类型 4 /// <summary> 5 /// 转成dictionary类型 6 /// </summary> 7 /// <param name="enumType"></param> 8 /// <returns></returns> 9 public static Dictionary<int, string> EnumToDictionary(this Type enumType) 10 { 11 Dictionary<int, string> dictionary = new Dictionary<int, string>(); 12 Type typeDescription = typeof(DescriptionAttribute); 13 FieldInfo[] fields = enumType.GetFields(); 14 int sValue = 0; 15 string sText = string.Empty; 16 foreach (FieldInfo field in fields) 17 { 18 if (field.FieldType.IsEnum) 19 { 20 sValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)); 21 object[] arr = field.GetCustomAttributes(typeDescription, true); 22 if (arr.Length > 0) 23 { 24 DescriptionAttribute da = (DescriptionAttribute)arr[0]; 25 sText = da.Description; 26 } 27 else 28 { 29 sText = field.Name; 30 } 31 dictionary.Add(sValue, sText); 32 } 33 } 34 return dictionary; 35 } 36 /// <summary> 37 /// 枚举成员转成键值对Json字符串 38 /// </summary> 39 /// <param name="enumType"></param> 40 /// <returns></returns> 41 //public static string EnumToDictionaryString(this Type enumType) 42 //{ 43 // List<KeyValuePair<int, string>> dictionaryList = EnumToDictionary(enumType).ToList(); 44 // var sJson = JsonConvert.SerializeObject(dictionaryList); 45 // return sJson; 46 //} 47 #endregion 48 49 #region 获取枚举的描述 50 /// <summary> 51 /// 获取枚举值对应的描述 52 /// </summary> 53 /// <param name="enumType"></param> 54 /// <returns></returns> 55 public static string GetDescription(this System.Enum enumType) 56 { 57 FieldInfo EnumInfo = enumType.GetType().GetField(enumType.ToString()); 58 if (EnumInfo != null) 59 { 60 DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])EnumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); 61 if (EnumAttributes.Length > 0) 62 { 63 return EnumAttributes[0].Description; 64 } 65 } 66 return enumType.ToString(); 67 } 68 #endregion 69 70 #region 根据值获取枚举的描述 71 public static string GetDescriptionByEnum<T>(this object obj) 72 { 73 var tEnum = System.Enum.Parse(typeof(T), obj.ParseToString()) as System.Enum; 74 var description = tEnum.GetDescription(); 75 return description; 76 } 77 #endregion 78 }