0

很奇怪,我找不到类似的问题,但这就是我真正想要的,找到派生类的所有父类。

我测试了一个代码,希望它对我有用:

void WriteInterfaces()
{
    var derivedClass = new DerivedClass();
    var type = derivedClass.GetType();
    var interfaces = type.FindInterfaces((objectType, criteria) =>
                                            objectType.Name == criteria.ToString(),"BaseClass");

    foreach(var face in interfaces)
    {
        face.Name.Dump();
    }
}

interface BaseInterface
{}

class BaseClass : BaseInterface {}

class BaseClass2 : BaseClass {}

class DerivedClass : BaseClass2{}

基本上,我的主要目的是检查派生类是否以某种方式继承了其基层次结构中的某个基类。

但是,此代码返回 null 并且仅适用于接口。

4

1 回答 1

5

It sounds like you don't actually need all the other types - you just need Type.IsSubclassOf or Type.IsAssignableFrom. However, getting all the type in the hierarchy is easy using Type.BaseType:

public static IEnumerable<Type> GetClassHierarchy(Type type)
{
    while (type != null)
    {
        yield return type;
        type = type.BaseType;
    }
}
于 2013-07-29T22:30:33.763 回答