Getting attributes of Enum's value

后端 未结 25 3013
慢半拍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:15

    Guys if it helps I will share with you my solution: Definition of Custom attribute:

        [AttributeUsage(AttributeTargets.Field,AllowMultiple = false)]
    public class EnumDisplayName : Attribute
    {
        public string Name { get; private set; }
        public EnumDisplayName(string name)
        {
            Name = name;
        }
    }
    

    Now because I needed it inside of HtmlHelper definition of HtmlHelper Extension:

    public static class EnumHelper
    {
        public static string EnumDisplayName(this HtmlHelper helper,EPriceType priceType)
        {
            //Get every fields from enum
            var fields = priceType.GetType().GetFields();
            //Foreach field skipping 1`st fieldw which keeps currently sellected value
            for (int i = 0; i < fields.Length;i++ )
            {
                //find field with same int value
                if ((int)fields[i].GetValue(priceType) == (int)priceType)
                {
                    //get attributes of found field
                    var attributes = fields[i].GetCustomAttributes(false);
                    if (attributes.Length > 0)
                    {
                        //return name of found attribute
                        var retAttr = (EnumDisplayName)attributes[0];
                        return retAttr.Name;
                    }
                }
            }
            //throw Error if not found
            throw new Exception("Błąd podczas ustalania atrybutów dla typu ceny allegro");
        }
    }
    

    Hope it helps

提交回复
热议问题