EnumExtension.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Collections.Concurrent;
  6. using System.Reflection;
  7. using System.ComponentModel.DataAnnotations;
  8. using System.ComponentModel;
  9. namespace Bowin.Common.Utility
  10. {
  11. /// <summary>
  12. /// Enum 的扩展
  13. /// </summary>
  14. public static class EnumExtension
  15. {
  16. private static ConcurrentDictionary<string, string> _cache = new ConcurrentDictionary<string, string>();
  17. public static string GetDisplayName(this Enum source)
  18. {
  19. var enumType = source.GetType();
  20. string name = Enum.GetName(enumType, source);
  21. var key = string.Concat(enumType.Name, "-", name);
  22. if (_cache.ContainsKey(key))
  23. {
  24. return _cache[key];
  25. }
  26. var enumDisplay = source.GetAttribute<DisplayAttribute>();
  27. if (enumDisplay != null)
  28. {
  29. _cache[key] = enumDisplay.Name;
  30. return enumDisplay.Name;
  31. }
  32. var enumDescription = source.GetAttribute<DescriptionAttribute>();
  33. if (enumDescription != null)
  34. {
  35. _cache[key] = enumDescription.Description;
  36. return enumDescription.Description;
  37. }
  38. _cache[key] = source.ToString();
  39. return source.ToString();
  40. }
  41. public static T GetAttribute<T>(this Enum source) where T : Attribute
  42. {
  43. Type enumType = source.GetType();
  44. string name = Enum.GetName(enumType, source);
  45. if (name != null)
  46. {
  47. FieldInfo fieldInfo = enumType.GetField(name);
  48. if (fieldInfo != null)
  49. {
  50. return fieldInfo.GetAttribute<T>();
  51. }
  52. }
  53. return null;
  54. }
  55. }
  56. }