给定以下类层次结构

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();

如何确定BobGenericMyGenericClass继承的代码?

最佳答案

您正在寻找 GetGenericTypeDefinition :

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

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

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

10-08 11:52