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

时间:2015-05-19 14:09:49

标签: c# generics type-parameter

我们说我们有这种类结构:

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
  • <and also where U inherits/implements same parent as T>表示满意,因为BC都实现了A1
  • 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不实现。

这可能吗?

(我认为我已经使用了“父母”这个词,但希望它仍然清晰)

1 个答案:

答案 0 :(得分:4)

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

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

现在你可以DoSomething<D, E, A1>()而不是DoSomething<B, D, A1>()