简体   繁体   English

确定类是否是具有多个通用参数的类型的子类

[英]Determine if class is a subclass of a type with multiple generic parameters

Given the following class hierarchy 给定以下类层次结构

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>{}

I would have thought that I could do the following 我原以为我可以做到以下几点

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

How would I determine in code that BobGeneric inherits from MyGenericClass ? 我如何在代码中确定BobGeneric继承自MyGenericClass

You're looking for GetGenericTypeDefinition : 您正在寻找GetGenericTypeDefinition

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

You can imagine that method as "stripping away" all generic type arguments, just leaving the raw definition with its formal generic parameters. 您可以将该方法想象为“剥离”所有泛型类型参数,只留下原始定义及其正式的通用参数。

If it does not work directly on BobGeneric , you may have to navigate upwards in the type hierarchy till you find MyGenericClass<...,...> (or any type for which IsGenericType returns true ). 如果它不能直接在BobGenericBobGeneric ,则可能必须在类型层次结构中向上导航,直到找到MyGenericClass<...,...> (或IsGenericType返回true任何类型)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM