EnumHelper.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace Common
  8. {
  9. public static class EnumHelper
  10. {
  11. /// <summary>
  12. /// 私有,,获取彩种配置的方法
  13. /// </summary>
  14. /// <returns></returns>
  15. public static IEnumerable<EnumModel> GetEnumList<T>()
  16. {
  17. var list = new List<EnumModel>();
  18. foreach (var field in typeof(T).GetFields())
  19. {
  20. if (!field.IsSpecialName)
  21. {
  22. var d = field.GetCustomAttributes(typeof(DescriptionAttribute), true);
  23. var o = field.GetCustomAttributes(typeof(OtherAttribute), true);
  24. list.Add(new EnumModel
  25. {
  26. Key = field.Name,
  27. Value = (int)field.GetRawConstantValue(),
  28. Description = d.Count() > 0 ? (d[0] as DescriptionAttribute).Description : "",
  29. Other = o.Count() > 0 ? (o[0] as OtherAttribute).Name : "",
  30. });
  31. }
  32. }
  33. return list;
  34. }
  35. /// <summary>
  36. /// 通过key获取EnumModel
  37. /// </summary>
  38. /// <param name="list"></param>
  39. /// <param name="value"></param>
  40. /// <returns></returns>
  41. public static EnumModel GetEnumModelByKey(this List<EnumModel> list, string value)
  42. {
  43. return list.Where(p => p.Key == value).FirstOrDefault();
  44. }
  45. public static EnumModel GetEnumModelByKey(this List<EnumModel> list, Enum value)
  46. {
  47. return list.Where(p => p.Key == value.ToString()).FirstOrDefault();
  48. }
  49. /// <summary>
  50. /// 根据EnumModel的Enum获取相应的详情
  51. /// </summary>
  52. /// <param name="list"></param>
  53. /// <param name="value"></param>
  54. /// <returns></returns>
  55. public static string GetEnumDescription(this List<EnumModel> list, Enum value)
  56. {
  57. return list.Where(p => p.Key == value.ToString()).FirstOrDefault().Description;
  58. }
  59. }
  60. }