Reputation: 30298
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;
}
Upvotes: 7
Views: 14668
Reputation: 8922
As found on .Net Framework Core official GitHub
page, use the following
type.GetTypeInfo().GetCustomAttributes()
github link for more information
Upvotes: 3
Reputation: 49779
You need to use GetCustomAttribute
method:
using System.Reflection;
...
typeof(<class name>).GetTypeInfo()
.GetProperty(<property name>).GetCustomAttribute<YourAttribute>();
Upvotes: 5
Reputation: 1062915
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.
Upvotes: 11