Dynamically Accessing Class Attributes in C#
Accessing class attributes at runtime is a powerful technique for retrieving metadata or configuration information dynamically. This can be achieved using C#'s reflection capabilities.
Retrieving a Specific Attribute (DomainNameAttribute):
A generic method, GetDomainName<T>
, simplifies retrieving a DomainNameAttribute
from any class:
<code class="language-csharp">public string GetDomainName<T>() { var dnAttribute = typeof(T).GetCustomAttributes(typeof(DomainNameAttribute), true) .FirstOrDefault() as DomainNameAttribute; return dnAttribute?.Name; }</code>
Usage example:
<code class="language-csharp">// Returns "MyTable" (assuming myclass has the attribute) string domainName = GetDomainName<myclass>();</code>
A More General Approach for Attribute Access:
For broader applicability, a more generalized extension method allows retrieval of any attribute type and its specific property:
<code class="language-csharp">public static class AttributeExtensions { public static TValue GetAttributeValue<TAttribute, TValue>( this Type type, Func<TAttribute, TValue> valueSelector) where TAttribute : Attribute { var attribute = type.GetCustomAttributes(typeof(TAttribute), true) .FirstOrDefault() as TAttribute; return attribute != null ? valueSelector(attribute) : default(TValue); } }</code>
Usage example:
<code class="language-csharp">string name = typeof(MyClass).GetAttributeValue((DomainNameAttribute dna) => dna.Name);</code>
This method takes the attribute type, and a lambda expression to select the desired property value from the attribute instance. This provides flexibility for accessing various attribute properties.
The above is the detailed content of How Can I Read Class Attributes at Runtime in C#?. For more information, please follow other related articles on the PHP Chinese website!