Advertisement
Guest User

Untitled

a guest
Feb 19th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.04 KB | None | 0 0
  1.  public static class EnumHelper
  2.     {
  3.         public static T GetAttribute<T>(this Enum value) where T : Attribute
  4.         {
  5.             var type = value.GetType();
  6.             var memberInfo = type.GetMember(value.ToString());
  7.             var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);
  8.             return (T)attributes[0];
  9.         }
  10.  
  11.         public static string ToDescription(this Enum value)
  12.         {
  13.             var attribute = value.GetAttribute<DescriptionAttribute>();
  14.             return attribute == null ? value.ToString() : attribute.Description;
  15.         }
  16.  
  17.         public static List<string> GetAttributeDescriptions<T>() where T : struct, IConvertible
  18.         {
  19.             if (!typeof(T).IsEnum)
  20.                 throw new ArgumentException("T must be an enumerated type");
  21.             var items = new List<string>();
  22.             foreach (Enum item in Enum.GetValues(typeof(T)))
  23.             {
  24.                 items.Add(item.ToDescription());
  25.             }
  26.             return items;
  27.         }
  28.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement