How to get Custom Attribute values for enums?

前端 未结 6 1586
独厮守ぢ
独厮守ぢ 2020-12-05 12:45

I have an enum where each member has a custom attribute applied to it. How can I retrieve the value stored in each attribute?

Right now I do this:

va         


        
6条回答
  •  天涯浪人
    2020-12-05 13:29

    Try using a generic method

    Attribute:

    class DayAttribute : Attribute
    {
        public string Name { get; private set; }
    
        public DayAttribute(string name)
        {
            this.Name = name;
        }
    }
    

    Enum:

    enum Days
    {
        [Day("Saturday")]
        Sat,
        [Day("Sunday")]
        Sun,
        [Day("Monday")]
        Mon, 
        [Day("Tuesday")]
        Tue,
        [Day("Wednesday")]
        Wed,
        [Day("Thursday")]
        Thu, 
        [Day("Friday")]
        Fri
    }
    

    Generic method:

            public static TAttribute GetAttribute(this Enum value)
            where TAttribute : Attribute
        {
            var enumType = value.GetType();
            var name = Enum.GetName(enumType, value);
            return enumType.GetField(name).GetCustomAttributes(false).OfType().SingleOrDefault();
        }
    

    Invoke:

            static void Main(string[] args)
        {
            var day = Days.Mon;
            Console.WriteLine(day.GetAttribute().Name);
            Console.ReadLine();
        }
    

    Result:

    Monday

提交回复
热议问题