如何在运行时读取类的属性? [英] How do I read an attribute on a class at runtime?

查看:23
本文介绍了如何在运行时读取类的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个通用方法,该方法将读取类上的属性并在运行时返回该值.我该怎么做?

I am trying to create a generic method that will read an attribute on a class and return that value at runtime. How do would I do this?

注意:DomainName 属性属于 DomainNameAttribute 类.

[DomainName("MyTable")]
Public class MyClass : DomainBase
{}

我试图生成的内容:

//This should return "MyTable"
String DomainNameValue = GetDomainName<MyClass>();

推荐答案

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

<小时>

更新:

此方法可以进一步推广以适用于任何属性:

This method could be further generalized to work with any attribute:

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);
    }
}

并像这样使用:

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

这篇关于如何在运行时读取类的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆