我正在尝试检查一个属性是否有一个属性。以前可以这样做:
Attribute.IsDefined(propertyInfo, typeof(AttributeClass));
然而,我收到了一个警告,它在DNX Core 5.0中不可用(但在DNX 4.5.1中仍然可用)。
它还没有被实现吗?或者像其他类型/反射相关的东西一样已经被移动了吗?
我正在使用beta7。
我正在尝试检查一个属性是否有一个属性。以前可以这样做:
Attribute.IsDefined(propertyInfo, typeof(AttributeClass));
然而,我收到了一个警告,它在DNX Core 5.0中不可用(但在DNX 4.5.1中仍然可用)。
它还没有被实现吗?或者像其他类型/反射相关的东西一样已经被移动了吗?
我正在使用beta7。
编辑:
实际上在System.Reflection.Extensions
包中似乎有一个IsDefined
扩展方法。用法:
var defined = propertyInfo.IsDefined(typeof(AttributeClass));
您需要包含System.Reflection
命名空间。参考源代码可以在这里找到。除了MemberInfo
外,它还适用于Assembly
、Module
和ParameterInfo
。
相较于使用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>();
GetCustomAttributes
根本没有包含我的属性。 - SaphuA