Getting attributes of Enum's value

后端 未结 25 2597
慢半拍i
慢半拍i 2020-11-22 00:35

I would like to know if it is possible to get attributes of the enum values and not of the enum itself? For example, suppose I have the following <

25条回答
  •  臣服心动
    2020-11-22 01:08

    Get the dictionary from enum.

    public static IDictionary ToDictionary(this Type enumType)
    {
        return Enum.GetValues(enumType)
        .Cast()
        .ToDictionary(v => ((Enum)v).ToEnumDescription(), k => (int)k); 
    }
    
    
    

    Now call this like...

    var dic = typeof(ActivityType).ToDictionary();
    

    EnumDecription Ext Method

    public static string ToEnumDescription(this Enum en) //ext method
    {
        Type type = en.GetType();
        MemberInfo[] memInfo = type.GetMember(en.ToString());
        if (memInfo != null && memInfo.Length > 0)
        {
            object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attrs != null && attrs.Length > 0)
                return ((DescriptionAttribute)attrs[0]).Description;
        }
        return en.ToString();
    }
    
    public enum ActivityType
    {
        [Description("Drip Plan Email")]
        DripPlanEmail = 1,
        [Description("Modification")]
        Modification = 2,
        [Description("View")]
        View = 3,
        [Description("E-Alert Sent")]
        EAlertSent = 4,
        [Description("E-Alert View")]
        EAlertView = 5
    }
    

    提交回复
    热议问题