1
0

EnumExtensions.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using Admin.Core.Common.Output;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Linq;
  6. using System.Reflection;
  7. namespace Admin.Core.Common.Extensions
  8. {
  9. public static class EnumExtensions
  10. {
  11. public static string ToDescription(this Enum item)
  12. {
  13. string name = item.ToString();
  14. var desc = item.GetType().GetField(name)?.GetCustomAttribute<DescriptionAttribute>();
  15. return desc?.Description ?? name;
  16. }
  17. public static long ToInt64(this Enum item)
  18. {
  19. return Convert.ToInt64(item);
  20. }
  21. public static List<OptionOutput> ToList(this Enum value, bool ignoreNull = false)
  22. {
  23. var enumType = value.GetType();
  24. if (!enumType.IsEnum)
  25. return null;
  26. return Enum.GetValues(enumType).Cast<Enum>()
  27. .Where(m => !ignoreNull || !m.ToString().Equals("Null")).Select(x => new OptionOutput
  28. {
  29. Label = x.ToDescription(),
  30. Value = x
  31. }).ToList();
  32. }
  33. public static List<OptionOutput> ToList<T>(bool ignoreNull = false)
  34. {
  35. var enumType = typeof(T);
  36. if (!enumType.IsEnum)
  37. return null;
  38. return Enum.GetValues(enumType).Cast<Enum>()
  39. .Where(m => !ignoreNull || !m.ToString().Equals("Null")).Select(x => new OptionOutput
  40. {
  41. Label = x.ToDescription(),
  42. Value = x
  43. }).ToList();
  44. }
  45. }
  46. }