EnumExt.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace StandardLibrary
  8. {
  9. public static class EnumExt
  10. {
  11. public static bool TryParseEnum<T>(object value, out T result) where T : struct, Enum
  12. {
  13. result = default;
  14. if (Enum.IsDefined(typeof(T), value))
  15. {
  16. result = (T)Enum.ToObject(typeof(T), value);
  17. return true;
  18. }
  19. return false;
  20. }
  21. /// <summary>
  22. /// 获取枚举值的 Description 特性文本,如果没有则返回枚举名称
  23. /// </summary>
  24. public static string GetDescription(this Enum value)
  25. {
  26. var field = value.GetType().GetField(value.ToString());
  27. if (field == null) return value.ToString();
  28. var attribute = Attribute.GetCustomAttribute(
  29. field,
  30. typeof(DescriptionAttribute)) as DescriptionAttribute;
  31. return attribute?.Description ?? value.ToString();
  32. }
  33. }
  34. }