Home > Backend Development > C++ > How Can I Read Class Attributes at Runtime in C#?

How Can I Read Class Attributes at Runtime in C#?

Linda Hamilton
Release: 2025-01-12 08:55:42
Original
388 people have browsed it

How Can I Read Class Attributes at Runtime in C#?

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>
Copy after login

Usage example:

<code class="language-csharp">// Returns "MyTable" (assuming myclass has the attribute)
string domainName = GetDomainName<myclass>();</code>
Copy after login

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>
Copy after login

Usage example:

<code class="language-csharp">string name = typeof(MyClass).GetAttributeValue((DomainNameAttribute dna) => dna.Name);</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template