给定以下课程:
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)
已经谢谢了