How to get all descriptions of enum values with reflection?

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

    You need to find the DescriptionAttribute on each field, if it exists and then retrieve the Description attribute e.g.

    return enumType.GetFields()
                    .Select(f => (DescriptionAttribute)f.GetCustomAttribute(typeof(DescriptionAttribute)))
                    .Where(a => a != null)
                    .Select(a => a.Description)
    

    If you could have multiple descriptions on a field, you could do something like:

    FieldInfo[] fields = enumType.GetFields();
    foreach(FieldInfo field in fields)
    {
        var descriptionAttributes = field.GetCustomAttributes(false).OfType();
        foreach(var descAttr in descriptionAttributes)
        {
            yield return descAttr.Description;
        }
    }
    

    which is more similar to your existing approach.

提交回复
热议问题