Attribute.IsDefined 在 DNX Core 5.0 中去了哪里?
Where did Attribute.IsDefined go in DNX Core 5.0?
我正在尝试检查 属性 是否具有属性。这曾经是通过以下方式完成的:
Attribute.IsDefined(propertyInfo, typeof(AttributeClass));
但是我收到一条警告,它在 DNX Core 5.0 中不可用(它仍然在 DNX 4.5.1 中)。
它还没有实现还是像其他 type/reflection 相关的东西一样移动了?
我正在使用 beta7。
编辑:
System.Reflection.Extensions
包中实际上似乎有一个 IsDefined
扩展方法。用法:
var defined = propertyInfo.IsDefined(typeof(AttributeClass));
您需要包含 System.Reflection
命名空间。可以找到参考源代码here。除了 MemberInfo
,它还适用于 Assembly
、Module
和 ParameterInfo
。
与使用 GetCustomAttribute
相比 possibly faster。
原文post:
看起来它还没有移植到 .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>();
我正在尝试检查 属性 是否具有属性。这曾经是通过以下方式完成的:
Attribute.IsDefined(propertyInfo, typeof(AttributeClass));
但是我收到一条警告,它在 DNX Core 5.0 中不可用(它仍然在 DNX 4.5.1 中)。
它还没有实现还是像其他 type/reflection 相关的东西一样移动了?
我正在使用 beta7。
编辑:
System.Reflection.Extensions
包中实际上似乎有一个 IsDefined
扩展方法。用法:
var defined = propertyInfo.IsDefined(typeof(AttributeClass));
您需要包含 System.Reflection
命名空间。可以找到参考源代码here。除了 MemberInfo
,它还适用于 Assembly
、Module
和 ParameterInfo
。
与使用 GetCustomAttribute
相比 possibly faster。
原文post:
看起来它还没有移植到 .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>();