[英]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>
因为B
和C
实现了A1
DoSomething<D, E>()
因为D
和E
都实现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没有实现。 这可能吗?
(我认为我在那儿已在使用“父母”一词,但希望它仍然很清楚)
您唯一可以做的就是提供第三个通用类型参数,该参数可让您指定T
和U
必须实现的接口:
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.