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

本文关键字:基类 约束 类型参数 | 更新日期: 2023-09-27 17:49:49

假设我们有这样的类结构:

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

  • where T : A满足B实现A
  • where U : A满足- C实现A
  • BC实现了A1 ,满足<and also where U inherits/implements same parent as T>
  • DoSomething<D, E>()也是允许的,因为DE都实现了A2

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

  • where T : A满足B实现A
  • where U : A满足C实现A
  • <and also where U inherits/implements same thing as T>不满足,因为B实现了A1,而D没有。

这可能吗?

(我想我已经删掉了"父母"这个词的使用,但希望它仍然清楚)

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

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

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

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