为什么在 C# 中不允许这样做? alt text http://img706.imageshack.us/img706/7360/restriction.png
其实我很想能写
alias Y<A, B> : X<A, B>, X<B, A>
这里实际上需要统一;如果 A = B 则只定义一个方法。
最佳答案
想到的第一个原因如下。
class Example : Y<int,int> {
...
}
在这种情况下,类型 Y 两次实现相同的接口(interface),但可以有相同方法的不同实现。这会在编译器中为方法 Tx 在实现和调用中造成无法解决的歧义。
例如下面的问题。
class OtherExample<A,B> : Y<A,B> {
B Tx(A x) {
Console.WriteLine("Top method in the file");
return default(B);
}
A Tx(B x) {
Console.WriteLine("Bottom method in the file");
return default(A);
}
}
如果忽略统一错误,这是 Y<A,B>
的合法实现.现在假设用户执行了以下操作
var v1 = new OtherExample<int,int>();
v1.Tx(42);
在这种情况下究竟会发生什么?编译器或 CLR 将如何解决歧义?您将拥有具有相同签名的相同名称的方法。
关于c# - 类型参数统一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2428772/