.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?
PS我尝试了以下操作,但似乎引发异常。不确定异常是什么,因为它只会一起停止应用程序。我尝试将代码放在 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< T>()
, GetCustomAttributes< T>()
, 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< TAttribute>()
应该做您需要的一切。
In your case, member.GetCustomAttribute<TAttribute>()
should do everything you need.
这篇关于.NET Core中的System.Attribute.GetCustomAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!