在DNX Core 5.0中,Attribute.IsDefined去哪了?

8

我正在尝试检查一个属性是否有一个属性。以前可以这样做:

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

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

它还没有被实现吗?或者像其他类型/反射相关的东西一样已经被移动了吗?

我正在使用beta7。

1个回答

11

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

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

您需要包含System.Reflection命名空间。参考源代码可以在这里找到。除了MemberInfo外,它还适用于AssemblyModuleParameterInfo

相较于使用GetCustomAttribute,这种方法可能更快


原始帖子:

看起来似乎还没有移植到.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>();

感谢您的出色建议。不幸的是,它似乎不起作用。它总是返回 null。GetCustomAttributes 根本没有包含我的属性。 - SaphuA
@SaphuA 我添加了一个示例。你能展示一下你的代码是什么样子的吗? - Henk Mollema
糟糕,看来你是对的!不确定我在测试中做错了什么...谢谢! - SaphuA
这种方式和 Attribute.IsDefined 一样快吗?它没有任何开销吗? - Parsa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接