EnumHelper.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace SmartCoalApplication.Annotation.Enum
  9. {
  10. /// <summary>
  11. /// 枚举帮助类
  12. /// </summary>
  13. public class EnumHelper
  14. {
  15. /// <summary>
  16. /// 获取枚举项描述信息 例如GetEnumDesc(Days.Sunday)
  17. /// </summary>
  18. /// <param name="en">枚举项 如Days.Sunday</param>
  19. /// <returns></returns>
  20. public static string GetEnumDesc(System.Enum en)
  21. {
  22. Type type = en.GetType();
  23. MemberInfo[] memInfo = type.GetMember(en.ToString());
  24. if (memInfo != null && memInfo.Length > 0)
  25. {
  26. object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
  27. if (attrs != null && attrs.Length > 0)
  28. return ((DescriptionAttribute)attrs[0]).Description;
  29. }
  30. return en.ToString();
  31. }
  32. ///<summary>
  33. /// 获取枚举项+描述
  34. ///</summary>
  35. ///<param name="enumType">Type,该参数的格式为typeof(需要读的枚举类型)</param>
  36. ///<returns>键值对</returns>
  37. public static Dictionary<string, string> GetEnumItemDesc(Type enumType)
  38. {
  39. Dictionary<string, string> dic = new Dictionary<string, string>();
  40. FieldInfo[] fieldinfos = enumType.GetFields();
  41. foreach (FieldInfo field in fieldinfos)
  42. {
  43. if (field.FieldType.IsEnum)
  44. {
  45. Object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
  46. dic.Add(field.Name, ((DescriptionAttribute)objs[0]).Description);
  47. }
  48. }
  49. return dic;
  50. }
  51. ///<summary>
  52. /// 获取枚举值+描述
  53. ///</summary>
  54. ///<param name="enumType">Type,该参数的格式为typeof(需要读的枚举类型)</param>
  55. ///<returns>键值对</returns>
  56. public static Dictionary<string, string> GetEnumItemValueDesc(Type enumType)
  57. {
  58. Dictionary<string, string> dic = new Dictionary<string, string>();
  59. Type typeDescription = typeof(DescriptionAttribute);
  60. FieldInfo[] fields = enumType.GetFields();
  61. string strText = string.Empty;
  62. string strValue = string.Empty;
  63. foreach (FieldInfo field in fields)
  64. {
  65. if (field.FieldType.IsEnum)
  66. {
  67. strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
  68. object[] arr = field.GetCustomAttributes(typeDescription, true);
  69. if (arr.Length > 0)
  70. {
  71. DescriptionAttribute aa = (DescriptionAttribute)arr[0];
  72. strText = aa.Description;
  73. }
  74. else
  75. {
  76. strText = field.Name;
  77. }
  78. dic.Add(strValue, strText);
  79. }
  80. }
  81. return dic;
  82. }
  83. }
  84. }