Home > Backend Development > C++ > How Can I Dynamically Retrieve Class Attributes in C#?

How Can I Dynamically Retrieve Class Attributes in C#?

Linda Hamilton
Release: 2025-01-12 08:28:11
Original
157 people have browsed it

How Can I Dynamically Retrieve Class Attributes in C#?

Dynamicly obtain class attributes

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

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

This method can be used like this:

<code class="language-csharp">string domainNameValue = GetDomainName<MyClass>(); // 返回 "MyTable"</code>
Copy after login

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

How to use:

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

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!

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