C# 多个类型参数-约束到同一基类?
假设我们有这样的类结构:C# 多个类型参数-约束到同一基类?,c#,generics,type-parameter,C#,Generics,Type Parameter,假设我们有这样的类结构: 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
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>
public void DoSomething()
T:A在哪里
你在哪里
它需要允许DoSomething()
:
满足-其中T:A
实现B
A
-其中满足U:A
实现C
A
满意,因为
和B
都实现了C
A1
也是允许的,因为DoSomething()
和D
都实现了E
A2
DoSomething()
:
满足-其中T:A
实现B
A
-其中满足U:A
实现C
A
不满意,因为
实现了B
,而D没有A1
(我想我已经彻底改变了“parent”一词的用法,但希望它仍然很清楚)您唯一能做的就是提供第三个泛型类型参数,让您指定
T
和U
必须实现的接口:
public void DoSomething<T, U, V>()
where T : V
where U : V
where V : A
public void DoSomething()
T:V在哪里
U:V在哪里
其中V:A
现在您可以执行
DoSomething()
但不能执行DoSomething()
唯一可以执行的是提供第三个泛型类型参数,该参数将允许您指定T
和U
必须实现的接口:
public void DoSomething<T, U, V>()
where T : V
where U : V
where V : A
public void DoSomething()
T:V在哪里
U:V在哪里
其中V:A
现在你可以做
DoSomething()
但不能做DoSomething()
如果需要允许B,C
而不是B,D
为什么不在哪里T:A1在哪里U:A1
?@YuvalItzchakov稍微编辑了一点问题,以清楚-它还需要允许DoSomething()
因为D
和E
都实现了A2
您可以创建该方法的两个重载。一旦接受A1
和一个接受A2
。为什么不做where T:A
和where U:T
?@Luaan他不想允许像A1
和A2
这样的配对A
太大了。如果它需要允许B,C
而不是B,D
为什么不在哪里T:A1在哪里U:A1
?@YuvalItzchakov稍微编辑了一点问题以保持清晰-它还需要允许DoSomething()
因为D
和E
都实现了A2
您可以创建该方法的两个重载。一旦接受A1
和一个接受A2
。为什么不做where T:A
和where U:T
?@Luaan他不想允许像A1
和A2
这样的配对<代码>A太大。