2012-11-19 113 views
0

我想检查是否有类型定义的[DataContract]属性或继承有它的实例定义检查,如果类型具有或继承具有一定属性的类型

类型:

[DataContract] 
public class Base 
{ 
} 


public class Child : Base 
{ 
} 

// IsDefined(typeof(Child), typeof(DataContract)) should be true; 

的Attribute.IsDefined,并Attribute.GetCustomAttribute不看基类

任何人知道如何做到这一点不看基类的

回答

1

试试这个

public static bool IsDefined(Type t, Type attrType) 
{ 
    do { 
     if (t.GetCustomAttributes(attrType, true).Length > 0) { 
      return true; 
     } 
     t = t.BaseType; 
    } while (t != null); 
    return false; 
} 

我得到了这个念头,因为在您的评论的“递归”一词的递归调用做出来。这是一个扩展方法

public static bool IsDefined(this Type t, Type attrType) 
{ 
    if (t == null) { 
     return false; 
    } 
    return 
     t.GetCustomAttributes(attrType, true).Length > 0 || 
     t.BaseType.IsDefined(attrType); 
} 

这样称呼它

typeof(Child).IsDefined(typeof(DataContractAttribute)) 
+0

优良的递归:) – Omu

+0

当然,如果你想检查_interfaces_由类型实现,并且所有的基本接口递归地实现,但它稍微复杂一些。但是,我想,这超出了问题的范围。 –

4

GetCustomAttribute()GetCustomAttributes(bool inherit)方法中存在一个超负荷方法,该方法使用布尔值来确定是否在继承的类中执行搜索。但是,只有在您要搜索的属性是使用[AttributeUsage(AttributeTargets.?, Inherited = true)]属性定义的情况下才有效。

+0

+1,但我去掉'Customer'属性:) –

相关问题