多个类型参数 - 约束到相同的基数 class?
Multiple type parameters - constrain to same base class?
假设我们有这个 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 没有。
这可能吗?
(我想我已经扼杀了 'parent' 这个词的使用,但希望它仍然很清楚)
您唯一能做的就是提供第三个泛型类型参数,让您指定 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>()
。
假设我们有这个 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 没有。
这可能吗?
(我想我已经扼杀了 'parent' 这个词的使用,但希望它仍然很清楚)
您唯一能做的就是提供第三个泛型类型参数,让您指定 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>()
。