泛型类型的反射子类

IsK*_*nel 4 c# generics reflection

在以下场景中:

public class A<T> { }

public class B : A<AClass> { }
Run Code Online (Sandbox Code Playgroud)

是否可以在不指定 AClass(泛型参数)的情况下确定 B 是否是 A 的子类?如:

typeof(B).IsSubclassOf(A<>)
Run Code Online (Sandbox Code Playgroud)

Lee*_*Lee 5

是的,但您必须自己通过层次结构:

var instance = new B();
Type t = instance.GetType();

bool isA = false;
while(t != typeof(object))
{
    if(t.IsGenericType && t.GetGenericTypeDefinition() == typeof(A<>))
    {
        isA = true;
        break;
    }
    else
    {
        t = t.BaseType;
    }
}
Run Code Online (Sandbox Code Playgroud)