IsSubclassOf() 不适用于父级为泛型的子级,除非指定了泛型类型

Man*_*ani 0 c# generics reflection

给定以下课程:

class A<T> { ... }
class B1: A<int> { ... }
class B2: A<string> { ... }
class C: B1 { ... }
class D: B2 { ... }
Run Code Online (Sandbox Code Playgroud)

我们得到以下结果:

typeof(C).IsSubclassOf(typeof(A<>))        // returns false
typeof(C).IsSubclassOf(typeof(A<int>)   // returns true
Run Code Online (Sandbox Code Playgroud)

现在的问题是,如果我们不知道 B 的泛型类型是什么怎么办?那么我们如何确定我们的类型是否是泛型基类 A<> 的后代呢?

bool IsDescebdedFromA(object x)
{
   return typeof(x).IsSubclassOf(typeof(A<>));    // does not give correct result. we have to specify generic type.
}
Run Code Online (Sandbox Code Playgroud)

已经谢谢了

pok*_*oke 6

由于泛型类型A<>不是可以实例化的实际类型,因此不能有它的子类。因此,为了检查某个类型是否是泛型类型的子类A<>,您需要手动遍历类型层次结构。

例如,这可以如下所示:

bool IsSubclassOfGeneric(Type current, Type genericBase)
{
    do 
    {
        if (current.IsGenericType && current.GetGenericTypeDefinition() == genericBase)
            return true;
    }
    while((current = current.BaseType) != null);
    return false;
}
Run Code Online (Sandbox Code Playgroud)

像这样使用:

Console.WriteLine(IsSubclassOfGeneric(typeof(A<>), typeof(A<>)));
Console.WriteLine(IsSubclassOfGeneric(typeof(A<int>), typeof(A<>)));
Console.WriteLine(IsSubclassOfGeneric(typeof(B1), typeof(A<>)));
Console.WriteLine(IsSubclassOfGeneric(typeof(B2), typeof(A<>)));
Console.WriteLine(IsSubclassOfGeneric(typeof(C), typeof(A<>)));
Console.WriteLine(IsSubclassOfGeneric(typeof(D), typeof(A<>)));
Console.WriteLine(IsSubclassOfGeneric(typeof(string), typeof(A<>))); // false
Run Code Online (Sandbox Code Playgroud)