Home >Backend Development >C++ >How to Dynamically Read Attribute Values in C# at Runtime?
Read attribute values dynamically at runtime
In software development, you often encounter situations where you need to dynamically access properties associated with a class or object. This capability is critical for various scenarios such as reflection, configuration retrieval, and dynamic code generation.
This article explores how to implement dynamic attribute retrieval in C#, demonstrating two different methods:
1. Custom methods for specific attribute types:
To read the attribute value of a specific attribute type, such as the DomainName
attribute, you can define a custom method like this:
<code class="language-csharp">public string GetDomainName<T>() { var dnAttribute = typeof(T).GetCustomAttributes( typeof(DomainNameAttribute), true ).FirstOrDefault() as DomainNameAttribute; if (dnAttribute != null) { return dnAttribute.Name; } return null; }</code>
2. Generic extension methods for any property type:
To make the property retrieval process general and support any property type, you can create the following generic extension method:
<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>
Usage:
Both methods allow you to get the DomainName
attribute value at runtime, like this:
<code class="language-csharp">// 使用自定义方法 string domainNameValue = GetDomainName<MyClass>(); // 使用扩展方法 string name = typeof(MyClass) .GetAttributeValue((DomainNameAttribute dna) => dna.Name);</code>
The above is the detailed content of How to Dynamically Read Attribute Values in C# at Runtime?. For more information, please follow other related articles on the PHP Chinese website!