.NET Core 中的 System.Attribute.GetCustomAttribute [英] System.Attribute.GetCustomAttribute in .NET Core
问题描述
我正在尝试将以下方法(在 .NET Framework 4.6.2 中工作正常)转换为 .NET Core 1.1.
I'm trying to convert the following method (which works fine in .NET Framework 4.6.2) to .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;
}
这段代码给了我错误
属性不包含 GetCustomAttribute 的定义.
Attribute does not contain a definition for GetCustomAttribute.
知道与此等效的 .NET Core 应该是什么吗?
Any idea what the .NET Core equivalent of this should be?
附言我尝试了以下操作,但似乎抛出了异常.不确定异常是什么,因为它只是一起停止了应用程序.我尝试将代码放在 try catch
块中,但它仍然停止运行,因此我无法捕获异常.
P.S. I tried the following but it seems to throw an exception. 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.
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
、GetCustomAttributes
、GetCustomAttributes()
等.您可以改用它们.扩展方法在 System.Reflection.CustomAttributeExtensions
中声明,所以你需要一个 using
指令:
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. The extension methods are declared in System.Reflection.CustomAttributeExtensions
, so you'll need a using
directive of:
using System.Reflection;
在你的情况下,member.GetCustomAttribute
应该做你需要的一切.
In your case, member.GetCustomAttribute<TAttribute>()
should do everything you need.
这篇关于.NET Core 中的 System.Attribute.GetCustomAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!