Attribute.IsDefined在哪里进入DNX Core 5.0?

时间:2015-09-30 08:04:19

标签: c# asp.net-core dnx

我试图检查属性是否有属性。过去常常这样做:

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

但是我得到一个警告,它在DNX Core 5.0中不可用(它仍然在DNX 4.5.1中)。

它尚未实现或是否像其他类型/反射相关的东西一样移动?

我正在使用beta7。

1 个答案:

答案 0 :(得分:11)

修改
实际上System.Reflection.Extensions包中似乎有一个IsDefined扩展方法。用法:

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

您需要包含System.Reflection命名空间。可以找到参考源代码here。在MemberInfo旁边,它也适用于AssemblyModuleParameterInfo

这比使用GetCustomAttribute possibly faster

<小时/> 原帖:

看起来它还没有移植到.NET Core。同时您可以使用GetCustomAttribute来确定是否在属性上设置了属性:

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

您可以将其烘焙为扩展方法:

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;
    }
}

并像这样使用它:

bool defined = propertyInfo.IsAttributeDefined<AttributeClass>();