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

How Can I Dynamically Access Class Attributes in C# at Runtime?

Patricia Arquette
Release: 2025-01-12 07:36:43
Original
890 people have browsed it

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:

public string GetDomainName<T>()
{
    var dnAttribute = typeof(T).GetCustomAttributes(
        typeof(DomainNameAttribute), true
    ).FirstOrDefault() as DomainNameAttribute;
    if (dnAttribute != null)
    {
        return dnAttribute.Name;
    }
    return null;
}
Copy after login

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:

// 这应该返回 "MyTable"
String DomainNameValue = GetDomainName<MyClass>();
Copy after login

To generalize this functionality to any property, we can create an extension method:

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);
    }
}
Copy after login

How to use it:

string name = typeof(MyClass)
    .GetAttributeValue((DomainNameAttribute dna) => dna.Name);
Copy after login

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!

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