Extension.Enum.cs 3.1 KB

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