System.Attribute.GetCustomAttribute in .NET Core

时光怂恿深爱的人放手 提交于 2019-12-10 13:12:38

问题


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;
}

This code is giving me the error

Attribute does not contain a definition for GetCustomAttribute.

Any idea what the .NET Core equivalent of this should be?

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;
}

回答1:


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;

In your case, member.GetCustomAttribute<TAttribute>() should do everything you need.




回答2:


You need to use GetCustomAttribute method:

using System.Reflection;
...

typeof(<class name>).GetTypeInfo()
      .GetProperty(<property name>).GetCustomAttribute<YourAttribute>();



回答3:


As found on .Net Framework Core official GitHub page, use the following

type.GetTypeInfo().GetCustomAttributes()

github link for more information



来源:https://stackoverflow.com/questions/43247759/system-attribute-getcustomattribute-in-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!