[英]System.Attribute.GetCustomAttribute in .NET Core
I'm trying to convert the following method (which works fine in .NET Framework 4.6.2) to .NET Core 1.1. 我正在尝试将以下方法(在.NET Framework 4.6.2中正常工作)转换为.NET Core 1.1。
public static TAttribute GetCustomAttribute<TAttribute>(MemberInfo member) where TAttribute : Attribute
{
var attr = System.Attribute.GetCustomAttribute(member, typeof(TAttribute));
if (attr is TAttribute)
return attr;
else
return null;
}
This code is giving me the error 这段代码给了我错误
Attribute does not contain a definition for GetCustomAttribute.
Attribute不包含GetCustomAttribute的定义。
Any idea what the .NET Core equivalent of this should be? 知道.NET Core相当于什么吗?
PS I tried the following but it seems to throw an exception. PS我尝试了以下但它似乎抛出异常。 Not sure what the exception is because it just stops the app all together.
不确定异常是什么,因为它只是一起停止应用程序。 I tried putting the code in a
try catch
block but still it just stops running so I couldn't capture the exception. 我尝试将代码放在
try catch
块中,但它仍然停止运行,所以我无法捕获异常。
public static TAttribute GetCustomAttribute<TAttribute>(MemberInfo member) where TAttribute : Attribute
{
var attr = GetCustomAttribute<TAttribute>(member);
if (attr is TAttribute)
return attr;
else
return null;
}
If you add a package reference to System.Reflection.Extensions
or System.Reflection.TypeExtensions
, then MemberInfo
gets a lot of extension methods like GetCustomAttribute<T>()
, GetCustomAttributes<T>()
, GetCustomAttributes()
, etc. You use those instead. 如果您向
System.Reflection.Extensions
或System.Reflection.TypeExtensions
添加包引用,则MemberInfo
会获取许多扩展方法,如GetCustomAttribute<T>()
, GetCustomAttributes<T>()
, GetCustomAttributes()
等。您使用那些而不是。 The extension methods are declared in System.Reflection.CustomAttributeExtensions
, so you'll need a using
directive of: 扩展方法在
System.Reflection.CustomAttributeExtensions
中声明,因此您需要一个using
指令:
using System.Reflection;
In your case, member.GetCustomAttribute<TAttribute>()
should do everything you need. 在您的情况下,
member.GetCustomAttribute<TAttribute>()
应该做您需要的一切。
You need to use GetCustomAttribute
method: 您需要使用
GetCustomAttribute
方法:
using System.Reflection;
...
typeof(<class name>).GetTypeInfo()
.GetProperty(<property name>).GetCustomAttribute<YourAttribute>();
As found on .Net Framework Core official GitHub
page, use the following 如
.Net Framework Core official GitHub
页面上所示,请使用以下内容
type.GetTypeInfo().GetCustomAttributes()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.