检查类型是否具有或继承具有特定属性的类型

Omu*_*Omu 1 .net c# reflection

我试图检查一个类型是否定义了 [DataContract] 属性或继承了一个定义了它的类型

例如:

[DataContract]
public class Base
{
}


public class Child : Base
{
}

// IsDefined(typeof(Child), typeof(DataContract)) should be true;
Run Code Online (Sandbox Code Playgroud)

Attribute.IsDefined 和 Attribute.GetCustomAttribute 不看基类

任何人都知道如何在不查看 BaseClass 的情况下执行此操作

Dmi*_* S. 5

GetCustomAttribute()GetCustomAttributes(bool inherit)方法有一个重载,它接受一个布尔值是否在继承的类中进行搜索。但是,它仅在您搜索的[AttributeUsage(AttributeTargets.?, Inherited = true)]属性是使用该属性定义的情况下才有效。