Enum to list as an extension?

后端 未结 6 1345
花落未央
花落未央 2021-02-19 19:00

I have various enums that I use as sources for dropdown lists, In order to provide for a user-friendly description, I added a Description attribute to each enum, an

6条回答
  •  忘了有多久
    2021-02-19 19:32

    You can create a generic method which would take Enum and Attribute as generic argument.

    For getting any attribute, you can create an extension method like:

    public static string AttributeValue(this TEnum value,Func func) where T : Attribute
    {
       FieldInfo field = value.GetType().GetField(value.ToString());
    
       T attribute = Attribute.GetCustomAttribute(field, typeof(T)) as T;
    
       return attribute == null ? value.ToString() : func(attribute);
    
    }  
    

    and here is the method for converting it to dictionary:

    public static Dictionary ToDictionary(this TEnum obj,Func func)
      where TEnum : struct, IComparable, IFormattable, IConvertible
      where TAttribute : Attribute
        {
    
            return (Enum.GetValues(typeof(TEnum)).OfType()
                .Select(x =>
                    new
                    {
                        Value = x,
                        Description = x.AttributeValue(func)
                    }).ToDictionary(x=>x.Value,x=>x.Description));
    
    
    
        }
    

    You can call it this way:

     var test =  eUserRole.SuperAdmin
                          .ToDictionary(attr=>attr.DisplayName); 
    

    I have used this Enum and Attribute as example:

    public class EnumDisplayNameAttribute : Attribute
    {
        private string _displayName;
        public string DisplayName
        {
            get { return _displayName; }
            set { _displayName = value; }
        }
    }  
    
    public enum eUserRole : int
    {
        [EnumDisplayName(DisplayName = "Super Admin")]
        SuperAdmin = 0,
        [EnumDisplayName(DisplayName = "Phoenix Admin")]
        PhoenixAdmin = 1,
        [EnumDisplayName(DisplayName = "Office Admin")]
        OfficeAdmin = 2,
        [EnumDisplayName(DisplayName = "Report User")]
        ReportUser = 3,
        [EnumDisplayName(DisplayName = "Billing User")]
        BillingUser = 4
    }
    

    Output:

提交回复
热议问题