gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:36:16 30 4
gpt4 key购买 nike

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

注意: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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com