本文介绍一种通用的方法,用于动态访问和提取类的属性值。
定义一个接受类型参数的通用方法:
public string GetDomainName<T>()
方法内部:
使用 typeof(T).GetCustomAttributes
检索自定义属性:
var dnAttribute = typeof(T).GetCustomAttributes( typeof(DomainNameAttribute), true ).FirstOrDefault() as DomainNameAttribute;
如果属性存在,则返回其值:
if (dnAttribute != null) { return dnAttribute.Name; }
否则,返回 null:
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;
如果属性存在,则使用提供的 valueSelector
来提取所需的值:
if (att != null) { return valueSelector(att); }
否则,返回该类型的默认值:
return default(TValue);
MyClass
的 DomainName
属性:string name = typeof(MyClass).GetDomainName<MyClass>();
MyClass
的任何属性值:string name = typeof(MyClass) .GetAttributeValue<DomainNameAttribute, string>((DomainNameAttribute dna) => dna.Name);
以上是如何在运行时动态检索类的属性值?的详细内容。更多信息请关注PHP中文网其他相关文章!