How to get all descriptions of enum values with reflection?

前端 未结 7 1473
孤独总比滥情好
孤独总比滥情好 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:11

    This generic static method works fine for getting a list of descriptions for each value of an enum type of T:

    public static IEnumerable GetDescriptions()
    {
        var attributes = typeof(T).GetMembers()
            .SelectMany(member => member.GetCustomAttributes(typeof (DescriptionAttribute), true).Cast())
            .ToList();
    
        return attributes.Select(x => x.Description);
    }
    

提交回复
热议问题