Home >Backend Development >C++ >How Can I Dynamically Retrieve Class Attributes in C#?
In object-oriented programming, attributes are metadata attached to a class, providing additional information beyond the code itself. If you need to dynamically read properties at runtime, here's how to do it.
Example of domain attributes
Consider the following code snippet containing the DomainName
attribute:
<code class="language-csharp">[DomainName("MyTable")] public class MyClass : DomainBase { }</code>
Generic methods for attribute reading
Our goal is to create a generic method that reads the DomainName
property on a given class and returns its value:
<code class="language-csharp">string GetDomainName<T>() { var dnAttribute = typeof(T).GetCustomAttributes( typeof(DomainNameAttribute), true ).FirstOrDefault() as DomainNameAttribute; if (dnAttribute != null) { return dnAttribute.Name; } return null; }</code>
This method can be used like this:
<code class="language-csharp">string domainNameValue = GetDomainName<MyClass>(); // 返回 "MyTable"</code>
Common attribute reading
Using the AttributeExtensions
class, property reading functionality can be generalized to work with any property type:
<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 att = type.GetCustomAttributes( typeof(TAttribute), true ).FirstOrDefault() as TAttribute; if (att != null) { return valueSelector(att); } return default(TValue); } }</code>
How to use:
<code class="language-csharp">string name = typeof(MyClass) .GetAttributeValue((DomainNameAttribute dna) => dna.Name);</code>
The above is the detailed content of How Can I Dynamically Retrieve Class Attributes in C#?. For more information, please follow other related articles on the PHP Chinese website!