EmunHelper.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 wispro.sp.entity
  9. {
  10. public class EnumnDescription<T>
  11. {
  12. public string Description { get; set; }
  13. public T Value { get; set; }
  14. }
  15. public class EnumHelper
  16. {
  17. /// <summary>
  18. /// 将枚举转换成描述字典集合
  19. /// </summary>
  20. /// <typeparam name="T">枚举类型</typeparam>
  21. /// <returns></returns>
  22. public static List<EnumnDescription<T>> getEnumDescriptionDic<T>()
  23. {
  24. List<EnumnDescription<T>> resultList = new List<EnumnDescription<T>>();
  25. Type type = typeof(T);
  26. var strList = Enum.GetNames(typeof(T)).ToList();
  27. foreach (string key in strList)
  28. {
  29. var obj = (T)Enum.Parse(type, key);
  30. FieldInfo field = obj.GetType().GetField(obj.ToString());
  31. DescriptionAttribute att = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute), false) as DescriptionAttribute;
  32. if (att == null)
  33. {
  34. resultList.Add(new EnumnDescription<T>() { Description = key, Value = obj });
  35. }
  36. else
  37. {
  38. resultList.Add(new EnumnDescription<T>() { Description = att.Description, Value = obj });
  39. }
  40. }
  41. return resultList;
  42. }
  43. public static string GetDescription<T>(T obj)
  44. {
  45. Type type = typeof(T);
  46. FieldInfo field = obj.GetType().GetField(obj.ToString());
  47. DescriptionAttribute att = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute), false) as DescriptionAttribute;
  48. if (att == null)
  49. {
  50. return obj.ToString();
  51. }
  52. else
  53. {
  54. return att.Description;
  55. }
  56. }
  57. }
  58. }