EnumExtensions.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System.ComponentModel;
  2. namespace AipGateway.API.Domain.Common.Extensions
  3. {
  4. public class EnumModel
  5. {
  6. public int Value { get; set; }
  7. public string? Name { get; set; }
  8. public string? Description { get; set; }
  9. public EnumModel(int iD, string? name, string? description)
  10. {
  11. Value = iD;
  12. Name = name;
  13. Description = description;
  14. }
  15. }
  16. public static class EnumExtensions
  17. {
  18. public static IEnumerable<EnumModel> ToList<T>() where T : struct, IConvertible
  19. {
  20. if (!typeof(T).IsEnum)
  21. return null;
  22. var values = Enum.GetValues(typeof(T)).Cast<T>();
  23. return values.Select(x => new EnumModel(Convert.ToInt32(x), x.ToString(), x.GetDescription()));
  24. }
  25. public static T ToEnum<T>(this string enumDescription) where T : struct, IConvertible
  26. {
  27. Enum.TryParse(enumDescription, true, out T result);
  28. return result;
  29. }
  30. public static T ToEnum<T>(this int enumValue) where T : struct, IConvertible
  31. {
  32. return Enum.Parse<T>(enumValue.ToString(), true);
  33. }
  34. public static string GetDescription<T>(this T enumValue) where T : struct, IConvertible
  35. {
  36. if (!typeof(T).IsEnum)
  37. return null;
  38. var description = enumValue.ToString();
  39. var fieldInfo = enumValue.GetType().GetField(enumValue.ToString() ?? string.Empty);
  40. if (fieldInfo != null)
  41. {
  42. var attrs = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), true);
  43. if (attrs != null && attrs.Length > 0)
  44. {
  45. description = ((DescriptionAttribute)attrs[0]).Description;
  46. }
  47. }
  48. return description ?? string.Empty;
  49. }
  50. }
  51. }