如何阅读在运行时类的属性? [英] How do I read an attribute on a class at runtime?
本文介绍了如何阅读在运行时类的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图创建将读取一个类的属性,并在运行时返回值的泛型方法。我怎么会这样?
注意:域名属性是类DomainNameAttribute的
。 [域名(MyTable的)]
公共类MyClass的:DomainBase
{}
我试图生成:
//这应该返回MyTable的
字符串DomainNameValue = GetDomainName< MyClass的>();
解决方案
公共字符串GetDomainName< T>()
{
VAR dnAttribute = typeof运算(T).GetCustomAttributes(
typeof运算(DomainNameAttribute),真
).FirstOrDefault()作为DomainNameAttribute;
如果(dnAttribute!= NULL)
{
返回dnAttribute.Name;
}
返回null;
}
更新:
该方法可以进一步推广与任何属性的工作:
公共静态类AttributeExtensions
{
公共静态TValue GetAttributeValue< TAttribute,TValue>(
这种类型的类型,
FUNC< TAttribute,TValue> valueSelector)
其中,TAttribute:属性
{
VAR ATT = type.GetCustomAttributes(
typeof运算(TAttribute),真
).FirstOrDefault()作为TAttribute;
如果(ATT!= NULL)
{
返回valueSelector(ATT);
}
返回默认值(TValue);
}
}
和使用这样的:
字符串名称= typeof运算(MyClass的)
.GetAttributeValue((DomainNameAttribute DNA)=> dna.Name);
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?
Note: DomainName attribute is of class DomainNameAttribute.
[DomainName("MyTable")]
Public class MyClass : DomainBase
{}
What I am trying to generate:
//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;
}
UPDATE:
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);
}
}
and use like this:
string name = typeof(MyClass)
.GetAttributeValue((DomainNameAttribute dna) => dna.Name);
这篇关于如何阅读在运行时类的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文