c# - 如何在运行时读取类的属性?

标签 c# generics custom-attributes

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

注意: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;
}

更新:

此方法可以进一步推广以处理任何属性:

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

关于c# - 如何在运行时读取类的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2656189/

相关文章:

asp.net-mvc-3 - MVC3 : Is it possible to change the result type outside of the code of the action itself?

c# - 如何接受 'dictionary' 数据作为自定义 .NET 属性参数?

c# - C# : operator '<' cannot be applied to operands of type 'T' and 'T' 中的比较

c# - HttpModule 未与 Visual Studio 一起运行

generics - 开放、封闭、绑定(bind)和非绑定(bind)通用类型

java - Eclipse content-assist 建议 <classname>.<parameter> 作为通用参数并报告错误

c# - list - 将选定的值放入一组标签(文本)

c# - PrintSystemJobInfo.TimeJobSubscribed 报告时间错误?

java - 不兼容类型 : SomeX cannot be converted to CAP#1

c# - 如何从 C# 中的子类型树获取属性的声明类型