输入参数统一

Ben*_*sen 4 c# generics unification

为什么在C#中不允许这样做? alt text http://img706.imageshack.us/img706/7360/restriction.png

其实我想写的

alias Y<A, B> : X<A, B>, X<B, A>
Run Code Online (Sandbox Code Playgroud)

这里实际上需要统一; 如果A = B则应该只定义一个方法.

Jar*_*Par 6

首先想到的是以下原因.

class Example : Y<int,int> {
 ...
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,类型Y实现两次相同的接口,但可以具有相同方法的不同实现.这在编译器中为实现和调用中的方法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);
  }
}
Run Code Online (Sandbox Code Playgroud)

如果忽略统一错误,这是合法的实现Y<A,B>.现在假设用户执行了以下操作

var v1 = new OtherExample<int,int>();
v1.Tx(42);
Run Code Online (Sandbox Code Playgroud)

在这种情况下究竟会发生什么?编译器或CLR如何能够解决这种模糊性?您将使用具有相同签名的相同名称的方法.