首页 >后端开发 >C++ >如何在 C# 中在运行时读取类属性?

如何在 C# 中在运行时读取类属性?

Linda Hamilton
Linda Hamilton原创
2025-01-12 08:55:42419浏览

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

在 C# 中动态访问类属性

在运行时访问类属性是动态检索元数据或配置信息的强大技术。 这可以使用 C# 的反射功能来实现。

检索特定属性(DomainNameAttribute):

通用方法 GetDomainName<T> 简化了从任何类检索 DomainNameAttribute 的过程:

<code class="language-csharp">public string GetDomainName<T>()
{
    var dnAttribute = typeof(T).GetCustomAttributes(typeof(DomainNameAttribute), true)
                               .FirstOrDefault() as DomainNameAttribute;
    return dnAttribute?.Name;
}</code>

使用示例:

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

属性访问的更通用方法:

为了更广泛的适用性,更通用的扩展方法允许检索任何属性类型及其特定属性:

<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>

使用示例:

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

此方法采用属性类型和 lambda 表达式来从属性实例中选择所需的属性值。 这为访问各种属性属性提供了灵活性。

以上是如何在 C# 中在运行时读取类属性?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn