Home > Backend Development > C++ > How to Dynamically Read Attribute Values in C# at Runtime?

How to Dynamically Read Attribute Values in C# at Runtime?

Patricia Arquette
Release: 2025-01-12 06:01:43
Original
360 people have browsed it

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

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

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

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!

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