This article introduces a general method for dynamically accessing and extracting attribute values of a class.
Define a generic method that accepts type parameters:
public string GetDomainName<T>()
Internal method:
Use typeof(T).GetCustomAttributes
to retrieve custom properties:
var dnAttribute = typeof(T).GetCustomAttributes( typeof(DomainNameAttribute), true ).FirstOrDefault() as DomainNameAttribute;
If the attribute exists, return its value:
if (dnAttribute != null) { return dnAttribute.Name; }
Otherwise, return null:
return null;
For wider applicability, generalize this method to handle any attribute:
public static class AttributeExtensions { public static TValue GetAttributeValue<TAttribute, TValue>( this Type type, Func<TAttribute, TValue> valueSelector) where TAttribute : Attribute }
Internal extension method:
Retrieve custom attributes:
var att = type.GetCustomAttributes( typeof(TAttribute), true ).FirstOrDefault() as TAttribute;
If the attribute exists, use the provided valueSelector
to extract the required value:
if (att != null) { return valueSelector(att); }
Otherwise, return the default value of the type:
return default(TValue);
MyClass
attribute of DomainName
: string name = typeof(MyClass).GetDomainName<MyClass>();
MyClass
using extension methods: string name = typeof(MyClass) .GetAttributeValue<DomainNameAttribute, string>((DomainNameAttribute dna) => dna.Name);
The above is the detailed content of How Can I Dynamically Retrieve Attribute Values from a Class at Runtime?. For more information, please follow other related articles on the PHP Chinese website!