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);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)