EnumHelper.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. namespace WCS.Utils
  6. {
  7. public class EnumHelper
  8. {
  9. public static string GetDescription(Enum value)
  10. {
  11. if (value == null)
  12. {
  13. throw new ArgumentException("value");
  14. }
  15. string description = value.ToString();
  16. var fieldInfo = value.GetType().GetField(description);
  17. var attributes =
  18. (EnumDescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(EnumDescriptionAttribute), false);
  19. if (attributes != null && attributes.Length > 0)
  20. {
  21. description = attributes[0].Description;
  22. }
  23. return description;
  24. }
  25. public static string GetEnumDescription<T>(string enumName) where T : Enum
  26. {
  27. Type enumType = typeof(T);
  28. if (!enumType.IsEnum)
  29. {
  30. throw new ArgumentException("T must be an enumerated type");
  31. }
  32. var enumField = enumType.GetField(enumName);
  33. if (enumField == null)
  34. {
  35. throw new ArgumentException($"No enum found with name {enumName} in {enumType}");
  36. }
  37. var attributes = (EnumDescriptionAttribute[])enumField.GetCustomAttributes(typeof(EnumDescriptionAttribute), false);
  38. return attributes.Length > 0 ? attributes[0].Description : enumName;
  39. }
  40. }
  41. }