[英]Multiple type parameters - constrain to same base class?
Let's say we have this class structure: 假设我们有这样的类结构:
interface A { }
interface A1 : A { }
interface A2 : A { }
class B : A1 { }
class C : A1 { }
class D : A2 { }
class E : A2 { }
And I want to declare a method with this header: 我想用此标头声明一个方法:
public void DoSomething<T, U>()
where T : A
where U : A
<and also where U inherits/implements same parent as T>
It needs to allow DoSomething<B, C>()
: 它需要允许
DoSomething<B, C>()
:
where T : A
is satisfied - B
implements A
where T : A
满足B
实现A
where U : A
is satisfied - C
implements A
where U : A
满足C
实现A
<and also where U inherits/implements same parent as T>
is satisfied because both B
and C
implement A1
<and also where U inherits/implements same parent as T>
因为B
和C
实现了A1
DoSomething<D, E>()
is also allowed because D
and E
both implement A2
DoSomething<D, E>()
因为D
和E
都实现A2
But it needs to not allow DoSomething<B, D>()
: 但是它不需要允许
DoSomething<B, D>()
:
where T : A
is satisfied - B
implements A
where T : A
满足B
实现A
where U : A
is satisfied - C
implements A
where U : A
满足C
实现A
<and also where U inherits/implements same thing as T>
is not satisfied because B
implements A1
but D does not. <and also where U inherits/implements same thing as T>
不能满足,因为B
实现了A1
而D没有实现。 Is this possible? 这可能吗?
(I think I've butchered the use of the word 'parent' there, but hopefully it's still clear) (我认为我在那儿已在使用“父母”一词,但希望它仍然很清楚)
The only thing you can do is to provide a third generic type parameter that will let you specify which interface both T
and U
have to implement: 您唯一可以做的就是提供第三个通用类型参数,该参数可让您指定
T
和U
必须实现的接口:
public void DoSomething<T, U, V>()
where T : V
where U : V
where V : A
Now you can do DoSomething<D, E, A1>()
but not DoSomething<B, D, A1>()
. 现在,您可以执行
DoSomething<D, E, A1>()
但不能执行DoSomething<B, D, A1>()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.