c# - 确定类是否是具有多个泛型参数的类型的子类

标签 c# generics inheritance

给定以下类层次结构

public abstract class MyGenericClass<T1, T2> 
{
    public T1 Foo { get; set; }
    public T2 Bar { get; set; }
}

public class BobGeneric : MyGenericClass<int, string>{}
public class JimGeneric : MyGenericClass<System.Net.Cookie, System.OverflowException>{}

我本以为我可以做到以下几点

//All types in the assembly containing BobGeneric and JimGeneric
var allTypes = _asm.GetTypes();  

//This works for interfaces, but not here 
var specialTypes = allTypes.Where(x => typeof(MyGenericClass<,>).IsAssignableFrom(x))

//This also fails
typeof(BobGeneric).IsSubclassOf(typeof(MyGenericClass<,>)).Dump();

我如何在代码中确定 BobGeneric 继承自 MyGenericClass

最佳答案

您正在寻找 GetGenericTypeDefinition :

typeof(BobGeneric).GetGenericTypeDefinition().IsSubclassOf(typeof(MyGenericClass<,>)).Dump();

您可以将该方法想象为“剥离”所有泛型类型参数,只留下原始定义及其形式泛型参数。

如果不能直接在BobGeneric上工作,您可能必须在类型层次结构中向上导航,直到找到 MyGenericClass<...,...> (或 IsGenericType 返回 true 的任何类型)。

关于c# - 确定类是否是具有多个泛型参数的类型的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17411105/

相关文章:

c# - .NET 中的 glob 模式匹配

c# - 将字符串转换为日期时间给出了错误的结果

Java类反射: init external class with wild card parameters

java - 列表的子类化如何工作?

c++ - 避免复制子类中的所有构造函数

javascript - 如何从 JSON 继承获取 JavaScript 对象?

c# - 当 CPU 使用率在一段时间内超过限制时发出警报

c# - 在 C# 的嵌套函数中分配的捕获变量在哪里

java - 为什么这个泛型代码没有运行时错误?

java - Java 8 中的接口(interface)