多个类型参数 - 约束到相同的基数 class?

Multiple type parameters - constrain to same base class?

假设我们有这个 class 结构:

interface A { }
interface A1 : A { }
interface A2 : A { }
class B : A1 { }
class C : A1 { }
class D : A2 { }
class E : A2 { }

我想用这个头文件声明一个方法:

public void DoSomething<T, U>()
    where T : A
    where U : A
    <and also where U inherits/implements same parent as T>

需要允许 DoSomething<B, C>():

但需要不允许 DoSomething<B, D>():

这可能吗?

(我想我已经扼杀了 'parent' 这个词的使用,但希望它仍然很清楚)

您唯一能做的就是提供第三个泛型类型参数,让您指定 TU 必须实现的接口:

public void DoSomething<T, U, V>()
    where T : V
    where U : V
    where V : A

现在您可以 DoSomething<D, E, A1>() 但不能 DoSomething<B, D, A1>()