EnumExtension.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Resources;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. /// <summary>
  10. /// 枚举扩展
  11. /// </summary>
  12. public static class EnumExtension
  13. {
  14. /// <summary>
  15. /// 获取枚举描述
  16. /// </summary>
  17. /// <param name="enumType">枚举类型</param>
  18. /// <returns></returns>
  19. public static string GetEnumDisplayName(this Enum enumType)
  20. {
  21. try
  22. {
  23. Type type = enumType.GetType();
  24. var field = type.GetField(Enum.GetName(type, enumType));
  25. var attr = field.GetCustomAttribute<DisplayAttribute>();
  26. if (attr == null || string.IsNullOrWhiteSpace(attr.Name))
  27. return enumType.ToString();
  28. else
  29. return attr.Name;
  30. }
  31. catch
  32. {
  33. return string.Empty;
  34. }
  35. }
  36. public static T GetEnumByDisplayName<T>(this string displayName) where T : struct
  37. {
  38. Type type = typeof(T);
  39. string[] names = Enum.GetNames(type);
  40. string[] array = names;
  41. foreach (string text in array)
  42. {
  43. DisplayAttribute customAttribute = type.GetField(text).GetCustomAttribute<DisplayAttribute>();
  44. T result;
  45. if (customAttribute == null)
  46. {
  47. if (text == displayName && Enum.TryParse(text, out result))
  48. {
  49. return result;
  50. }
  51. continue;
  52. }
  53. string a;
  54. if (customAttribute.ResourceType == null && string.IsNullOrEmpty(customAttribute.Name))
  55. {
  56. a = text;
  57. }
  58. else if (!(customAttribute.ResourceType != null))
  59. {
  60. a = (string.IsNullOrEmpty(customAttribute.Name) ? text : customAttribute.Name);
  61. }
  62. else
  63. {
  64. ResourceManager resourceManager = new ResourceManager(customAttribute.ResourceType);
  65. a = resourceManager.GetString(customAttribute.Name);
  66. }
  67. if (a == displayName && System.Enum.TryParse(text, out result))
  68. {
  69. return result;
  70. }
  71. }
  72. return (T)System.Enum.Parse(type, "0");
  73. }
  74. }