Where did Attribute.IsDefined go in DNX Core 5.0?

 ̄綄美尐妖づ 提交于 2019-12-19 16:33:26

问题


I'm trying to check if a property has an attribute. This used to be done with:

Attribute.IsDefined(propertyInfo, typeof(AttributeClass));

However I get a warning that it's not available in DNX Core 5.0 (it still is in DNX 4.5.1).

Has it not been implemented yet or has it moved like other type/reflection related stuff?

I'm using beta7.


回答1:


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>();


来源:https://stackoverflow.com/questions/32860947/where-did-attribute-isdefined-go-in-dnx-core-5-0

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