繁体   English   中英

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

[英]Multiple type parameters - constrain to same base 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>()

  • 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没有实现。

这可能吗?

(我认为我在那儿已在使用“父母”一词,但希望它仍然很清楚)

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

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

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

暂无
暂无

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

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