小编Man*_*ani的帖子

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

给定以下课程:

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)

已经谢谢了

c# generics reflection

0
推荐指数
1
解决办法
1356
查看次数

标签 统计

c# ×1

generics ×1

reflection ×1