DNX Core 5.0中Attribute.IsDefined放在哪里? [英] Where did Attribute.IsDefined go in DNX Core 5.0?
问题描述
我正在尝试检查属性是否具有属性.过去,这是通过以下方式完成的:
I'm trying to check if a property has an attribute. This used to be done with:
Attribute.IsDefined(propertyInfo, typeof(AttributeClass));
但是我收到警告,说它在DNX Core 5.0中不可用(它仍然在DNX 4.5.1中).
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?
我正在使用beta7.
I'm using beta7.
推荐答案
实际上,在 System.Reflection.Extensions
包中似乎有一个IsDefined
扩展方法. .用法:
There actually seems to be an IsDefined
extension method in the System.Reflection.Extensions
package. Usage:
var defined = propertyInfo.IsDefined(typeof(AttributeClass));
您需要包括System.Reflection
命名空间.可以在此处.在MemberInfo
旁边,它也可以在Assembly
,Module
和ParameterInfo
上工作.
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.
这比使用GetCustomAttribute
可能更快.
原始帖子:
看起来它尚未移植到.NET Core.同时,您可以使用GetCustomAttribute
来确定是否在属性上设置了属性:
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;
}
}
并像这样使用它:
bool defined = propertyInfo.IsAttributeDefined<AttributeClass>();
这篇关于DNX Core 5.0中Attribute.IsDefined放在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!