我正在尝试将以下方法(在 .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;
}
这段代码给我错误
Attribute does not contain a definition for GetCustomAttribute.
知道与此对应的 .NET Core 应该是什么吗?
附言我尝试了以下但它似乎抛出异常。不确定异常是什么,因为它只是一起停止了应用程序。我尝试将代码放在 try catch
block 中,但它仍然只是停止运行,所以我无法捕获异常。
public static TAttribute GetCustomAttribute<TAttribute>(MemberInfo member) where TAttribute : Attribute
{
var attr = GetCustomAttribute<TAttribute>(member);
if (attr is TAttribute)
return attr;
else
return null;
}
最佳答案
如果添加对 System.Reflection.Extensions
的包引用或 System.Reflection.TypeExtensions
, 然后 MemberInfo
得到很多扩展方法,比如 GetCustomAttribute<T>()
, GetCustomAttributes<T>()
, GetCustomAttributes()
等。您改用那些。扩展方法在 System.Reflection.CustomAttributeExtensions
中声明, 所以你需要一个 using
指令:
using System.Reflection;
在你的例子中,member.GetCustomAttribute<TAttribute>()
应该做你需要的一切。
关于c# - .NET Core 中的 System.Attribute.GetCustomAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43247759/