Where did Attribute.IsDefined go in DNX Core 5.0?

非 Y 不嫁゛ 提交于 2019-12-01 16:04:28
Henk Mollema

Edit:
There actually seems to be an IsDefined extension method in the System.Reflection.Extensions package. Usage:

var defined = propertyInfo.IsDefined(typeof(AttributeClass));

You need to include the System.Reflection namespace. The reference source code can be found here. Beside MemberInfo, it works on Assembly, Module and ParameterInfo too.

This is possibly faster than using GetCustomAttribute.


Original post:

Looks like it's not ported to .NET Core yet. In the mean while you can use GetCustomAttribute to determine whether an attribute is set on a property:

bool defined = propertyInfo.GetCustomAttribute(typeof(AttributeClass)) != null;

You could bake this into an extension method:

public static class MemberInfoExtensions
{
    public static bool IsAttributeDefined<TAttribute>(this MemberInfo memberInfo)
    {
        return memberInfo.IsAttributeDefined(typeof(TAttribute));
    }

    public static bool IsAttributeDefined(this MemberInfo memberInfo, Type attributeType)
    {
        return memberInfo.GetCustomAttribute(attributeType) != null;
    }
}

And use it like this:

bool defined = propertyInfo.IsAttributeDefined<AttributeClass>();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!