Home >Backend Development >C++ >How Can I Dynamically Access Class Attributes in C# at Runtime?
Dynamic access to class attributes at runtime
In object-oriented programming, attributes provide additional metadata for classes and their members. Retrieving property values at runtime is useful for accessing class-specific information or custom behavior. This article explores a way to read property values assigned to a class at runtime.
Suppose we need to get the "DomainName" property from the "MyClass" class. This attribute is of type "DomainNameAttribute" and has the value "MyTable". The goal is to create a generic method that dynamically reads this property and returns its value.
For this we can leverage the .NET reflection feature:
<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>
In this code, we use the "GetCustomAttributes" method to retrieve all the attributes of type "DomainNameAttribute" from the specified type. We then cast the first (and usually only) attribute to type "DomainNameAttribute". If the property exists, its "Name" property is returned. Otherwise, return null.
Using this method, we can dynamically retrieve the "DomainName" property value at runtime:
<code class="language-csharp">// 这应该返回 "MyTable" String DomainNameValue = GetDomainName<MyClass>();</code>
To generalize this functionality to any property, we can create an 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>
How to use it:
<code class="language-csharp">string name = typeof(MyClass) .GetAttributeValue((DomainNameAttribute dna) => dna.Name);</code>
This generalized extension method provides the flexibility to access any property associated with the type, making it a versatile tool for inspecting class properties at runtime.
The above is the detailed content of How Can I Dynamically Access Class Attributes in C# at Runtime?. For more information, please follow other related articles on the PHP Chinese website!