Sam*_*Sam 6 c# reflection system.reflection .net-core
我正在尝试将以下方法(在.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;
}
Run Code Online (Sandbox Code Playgroud)
这段代码给了我错误
Attribute不包含GetCustomAttribute的定义.
知道.NET Core相当于什么吗?
PS我尝试了以下但它似乎抛出异常.不确定异常是什么,因为它只是一起停止应用程序.我尝试将代码放在一个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;
}
Run Code Online (Sandbox Code Playgroud)
如果添加一个包引用System.Reflection.Extensions或System.Reflection.TypeExtensions,然后MemberInfo得到了很多的扩展方法,如GetCustomAttribute<T>(),GetCustomAttributes<T>(),GetCustomAttributes(),等你用这些代替.扩展方法是声明的System.Reflection.CustomAttributeExtensions,因此您需要一个using指令:
using System.Reflection;
Run Code Online (Sandbox Code Playgroud)
在您的情况下,member.GetCustomAttribute<TAttribute>()应该做你需要的一切.
您需要使用GetCustomAttribute方法:
using System.Reflection;
...
typeof(<class name>).GetTypeInfo()
.GetProperty(<property name>).GetCustomAttribute<YourAttribute>();
Run Code Online (Sandbox Code Playgroud)