EnumExtension.cs 941 B

12345678910111213141516171819202122232425262728293031323334353637
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. /// <summary>
  9. /// 枚举扩展
  10. /// </summary>
  11. public static class EnumExtension
  12. {
  13. /// <summary>
  14. /// 获取枚举描述
  15. /// </summary>
  16. /// <param name="enumType">枚举类型</param>
  17. /// <returns></returns>
  18. public static string GetEnumDisplayName(this Enum enumType)
  19. {
  20. try
  21. {
  22. Type type = enumType.GetType();
  23. var field = type.GetField(Enum.GetName(type, enumType));
  24. var attr = field.GetCustomAttribute<DisplayAttribute>();
  25. if (attr == null || string.IsNullOrWhiteSpace(attr.Name))
  26. return enumType.ToString();
  27. else
  28. return attr.Name;
  29. }
  30. catch
  31. {
  32. return string.Empty;
  33. }
  34. }
  35. }