EnumExtensions.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. using System;
  2. using System.ComponentModel;
  3. using System.Reflection;
  4. namespace WCS_Client.Extensions
  5. {
  6. public static class EnumExtensions
  7. {
  8. /// <summary>
  9. /// 扩展方法,获得枚举的Description
  10. /// </summary>
  11. /// <param name="value">枚举值</param>
  12. /// <param name="nameInstead">当枚举值没有定义DescriptionAttribute,是否使用枚举名代替,默认是使用</param>
  13. /// <returns>枚举的Description</returns>
  14. public static string GetDescription(this Enum value, Boolean nameInstead = true)
  15. {
  16. Type type = value.GetType();
  17. string name = Enum.GetName(type, value);
  18. if (name == null)
  19. {
  20. return null;
  21. }
  22. FieldInfo field = type.GetField(name);
  23. DescriptionAttribute attribute = System.Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
  24. if (attribute == null && nameInstead == true)
  25. {
  26. return name;
  27. }
  28. return attribute?.Description;
  29. }
  30. }
  31. }