EnumHelper.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Collections.Concurrent;
  6. using System.ComponentModel;
  7. namespace Bowin.Common.Exceptions
  8. {
  9. public class EnumHelper
  10. {
  11. static ConcurrentDictionary<Type, Dictionary<int, string>> _listItemCache =
  12. new ConcurrentDictionary<Type, Dictionary<int, string>>();
  13. /// <summary>
  14. /// 将枚举转换成Dictionary&lt;int, string&gt;
  15. /// Dictionary中,key为枚举项对应的int值;value为:若定义了Description属性,则取它,否则取name
  16. /// </summary>
  17. /// <param name="enumType"></param>
  18. /// <returns></returns>
  19. public static Dictionary<int, string> EnumToDictionary(Type enumType)
  20. {
  21. Dictionary<int, string> items;
  22. if (!_listItemCache.TryGetValue(enumType, out items))
  23. {
  24. items = new Dictionary<int, string>();
  25. foreach (int i in Enum.GetValues(enumType))
  26. {
  27. var name = Enum.GetName(enumType, i);
  28. //取显示名称
  29. string showName = string.Empty;
  30. object[] atts = enumType.GetField(name).GetCustomAttributes(typeof(DescriptionAttribute), false);
  31. if (atts.Length > 0)
  32. showName = ((DescriptionAttribute)atts[0]).Description;
  33. items.Add(i, string.IsNullOrEmpty(showName) ? name : showName);
  34. }
  35. _listItemCache[enumType] = items;
  36. }
  37. return items;
  38. }
  39. /// <summary>
  40. /// 获取枚举值对应的显示名称
  41. /// </summary>
  42. /// <param name="enumType">枚举类型</param>
  43. /// <param name="value">枚举项对应的int值</param>
  44. /// <returns></returns>
  45. public static string GetEnumShowName(Type enumType, int value)
  46. {
  47. return EnumToDictionary(enumType)[value];
  48. }
  49. }
  50. }