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;
}
GetCustomAttribute(MemberInfo, Type) Retrieves a custom attribute applied to a member of a type. Parameters specify the member, and the type of the custom attribute to search for. GetCustomAttribute(Assembly, Type) Retrieves a custom attribute applied to a specified assembly.
Declaring Custom AttributesWe can define an attribute by creating a class. This class should inherit from the Attribute class. Microsoft recommends appending the 'Attribute' suffix to the end of the class's name. After that, each property of our derived class will be a parameter of the desired data type.
Determines how a custom attribute class can be used. AttributeUsage is an attribute that can be applied to custom attribute definitions to control how the new attribute can be applied. So it basically gives the compiler some extra information about the attribute class you will implement.
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.
You need to use GetCustomAttribute
method:
using System.Reflection;
...
typeof(<class name>).GetTypeInfo()
.GetProperty(<property name>).GetCustomAttribute<YourAttribute>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With