How to get Custom Attribute values for enums?

前端 未结 6 1585
独厮守ぢ
独厮守ぢ 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:18

    There is another method to do this with generics:

    public static T GetAttribute(Enum enumValue) where T: Attribute
    {
        T attribute;
    
        MemberInfo memberInfo = enumValue.GetType().GetMember(enumValue.ToString())
                                        .FirstOrDefault();
    
        if (memberInfo != null)
        {
            attribute = (T) memberInfo.GetCustomAttributes(typeof (T), false).FirstOrDefault();
            return attribute;
        }
        return null;
    }
    

提交回复
热议问题