给定以下类层次结构
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
?
答案 0 :(得分:7)
您正在寻找GetGenericTypeDefinition
:
typeof(BobGeneric).GetGenericTypeDefinition().IsSubclassOf(typeof(MyGenericClass<,>)).Dump();
您可以将该方法想象为“剥离”所有泛型类型参数,只留下原始定义及其正式通用参数。
如果它不能直接在BobGeneric
上运行,您可能需要在类型层次结构中向上导航,直到找到MyGenericClass<...,...>
(或IsGenericType
返回true
的任何类型})。