I am trying to create a generic method that will read an attribute on a class and return that value at runtime. How do would I do this?
Note: DomainName attribute is of class DomainNameAttribute.
[DomainName("MyTable")] Public class MyClass : DomainBase {}
What I am trying to generate:
//This should return "MyTable" String DomainNameValue = GetDomainName<MyClass>();
First, declare an instance of the attribute you want to retrieve. Then, use the Attribute. GetCustomAttribute method to initialize the new attribute to the value of the attribute you want to retrieve. Once the new attribute is initialized, you simply use its properties to get the values.
The same you would normally check for an attribute on a class. Here's some sample code. typeof(ScheduleController) . IsDefined(typeof(SubControllerActionToViewDataAttribute), false);
In C#, attributes are classes that inherit from the Attribute base class. Any class that inherits from Attribute can be used as a sort of "tag" on other pieces of code. For instance, there is an attribute called ObsoleteAttribute . This is used to signal that code is obsolete and shouldn't be used anymore.
AttributeUsage attribute defines the program entities to which the attribute can be applied. We can use reflection to discover information about a program entity at runtime and to create an instance of a type at runtime. Most of the classes and interfaces needed for reflection are defined in the System.
public string GetDomainName<T>() { var dnAttribute = typeof(T).GetCustomAttributes( typeof(DomainNameAttribute), true ).FirstOrDefault() as DomainNameAttribute; if (dnAttribute != null) { return dnAttribute.Name; } return null; }
UPDATE:
This method could be further generalized to work with any attribute:
public static class AttributeExtensions { public static TValue GetAttributeValue<TAttribute, TValue>( this Type type, Func<TAttribute, TValue> valueSelector) where TAttribute : Attribute { var att = type.GetCustomAttributes( typeof(TAttribute), true ).FirstOrDefault() as TAttribute; if (att != null) { return valueSelector(att); } return default(TValue); } }
and use like this:
string name = typeof(MyClass) .GetAttributeValue((DomainNameAttribute dna) => dna.Name);
There is already an extension to do this.
namespace System.Reflection { // Summary: // Contains static methods for retrieving custom attributes. public static class CustomAttributeExtensions { public static T GetCustomAttribute<T>(this MemberInfo element, bool inherit) where T : Attribute; } }
So:
var attr = typeof(MyClass).GetCustomAttribute<DomainNameAttribute>(false); return attr != null ? attr.DomainName : "";
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