How to get all descriptions of enum values with reflection?

前端 未结 7 1476
孤独总比滥情好
孤独总比滥情好 2021-02-10 08:29

So I need to get a List from my enum

Here is what I have done so far:

enum definition

           


        
7条回答
  •  青春惊慌失措
    2021-02-10 09:01

    Here is a small reusable solution. This is an abstract class which will extract all the attributes of type K from type T.

    abstract class AbstractAttributes
    {
        protected List Attributes = new List();
    
        public AbstractAttributes()
        {
            foreach (var member in typeof(T).GetMembers())
            {
                foreach (K attribute in member.GetCustomAttributes(typeof(K), true)) 
                    Attributes.Add(attribute);                
            }
        }
    }
    

    Should we now want to extract only attributes of DescriptionAttribute type, we would use the following class.

    class DescriptionAttributes : AbstractAttributes
    {
        public List Descriptions { get; set; }
    
        public DescriptionAttributes()
        {
            Descriptions = Attributes.Select(x => x.Description).ToList();
        }
    }
    

    This class will extract only attributes of DescriptionAttribute type from the type T. But to actually use this class in you context you will simply need to do the following.

    new DescriptionAttributes().Descriptions.ForEach(x => Console.WriteLine(x));
    

    This line of code will write out all the descriptions you used as parameters in your attributes of type DescriptionAttribute. Should you need to extract some other attributes, just create a new class that derives from the AbstractAttributes class and close its type K with the appropriate attribute.

提交回复
热议问题