多个类型参数-约束到相同的基类
本文关键字:基类 约束 类型参数 | 更新日期: 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
-
DoSomething<D, E>()
也是允许的,因为D
和E
都实现了A2
B
和C
实现了A1
,满足<and also where U inherits/implements same parent as T>
但是需要不允许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>()