You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.8 KiB

2 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. namespace EasyBL.WebApi.Common
  4. {
  5. public static class EnumExtension
  6. {
  7. private static Dictionary<string, Dictionary<string, string>> enumCache;
  8. private static Dictionary<string, Dictionary<string, string>> EnumCache
  9. {
  10. get
  11. {
  12. if (enumCache == null)
  13. {
  14. enumCache = new Dictionary<string, Dictionary<string, string>>();
  15. }
  16. return enumCache;
  17. }
  18. set { enumCache = value; }
  19. }
  20. public static string GetEnumText(this Enum en)
  21. {
  22. var enString = string.Empty;
  23. if (null == en) return enString;
  24. var type = en.GetType();
  25. enString = en.ToString();
  26. if (!EnumCache.ContainsKey(type.FullName))
  27. {
  28. var fields = type.GetFields();
  29. var temp = new Dictionary<string, string>();
  30. foreach (var item in fields)
  31. {
  32. var attrs = item.GetCustomAttributes(typeof(TextAttribute), false);
  33. if (attrs.Length == 1)
  34. {
  35. var v = ((TextAttribute)attrs[0]).Value;
  36. temp.Add(item.Name, v);
  37. }
  38. }
  39. EnumCache.Add(type.FullName, temp);
  40. }
  41. if (EnumCache[type.FullName].ContainsKey(enString))
  42. {
  43. return EnumCache[type.FullName][enString];
  44. }
  45. return enString;
  46. }
  47. }
  48. public sealed class TextAttribute : Attribute
  49. {
  50. public TextAttribute(string value)
  51. {
  52. Value = value;
  53. }
  54. public string Value { get; set; }
  55. }
  56. }