Home >Backend Development >C++ >How Can I Dynamically Retrieve Attribute Values from a Class at Runtime?
This article introduces a general method for dynamically accessing and extracting attribute values of a class.
Define a generic method that accepts type parameters:
<code class="language-csharp">public string GetDomainName<T>()</code>
Internal method:
Use typeof(T).GetCustomAttributes
to retrieve custom properties:
<code class="language-csharp"> var dnAttribute = typeof(T).GetCustomAttributes( typeof(DomainNameAttribute), true ).FirstOrDefault() as DomainNameAttribute;</code>
If the attribute exists, return its value:
<code class="language-csharp"> if (dnAttribute != null) { return dnAttribute.Name; }</code>
Otherwise, return null:
<code class="language-csharp"> return null;</code>
For wider applicability, generalize this method to handle any attribute:
<code class="language-csharp">public static class AttributeExtensions { public static TValue GetAttributeValue<TAttribute, TValue>( this Type type, Func<TAttribute, TValue> valueSelector) where TAttribute : Attribute }</code>
Internal extension method:
Retrieve custom attributes:
<code class="language-csharp"> var att = type.GetCustomAttributes( typeof(TAttribute), true ).FirstOrDefault() as TAttribute;</code>
If the attribute exists, use the provided valueSelector
to extract the required value:
<code class="language-csharp"> if (att != null) { return valueSelector(att); }</code>
Otherwise, return the default value of the type:
<code class="language-csharp"> return default(TValue);</code>
MyClass
attribute of DomainName
: <code class="language-csharp">string name = typeof(MyClass).GetDomainName<MyClass>();</code>
MyClass
using extension methods: <code class="language-csharp">string name = typeof(MyClass) .GetAttributeValue<DomainNameAttribute, string>((DomainNameAttribute dna) => dna.Name);</code>
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!