4

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

其实我希望能够写作

alias Y<A, B> : X<A, B>, X<B, A>

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

4

2 回答 2

6

The first reason that comes to mind is the following.

class Example : Y<int,int> {
 ...
}

In this case the type Y implements the same interface twice but can have differing implementations of the same method. This creates an unresolvable ambiguity in the compiler for the method Tx in both implementation and calling.

For example take the following problem.

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);
  }
}

If you ignore the unification error this is a legal implementation of Y<A,B>. Now imagine the user did the following

var v1 = new OtherExample<int,int>();
v1.Tx(42);

What exactly would happen in this scenario? How would the compiler, or the CLR for that matter, be able to resolve the ambiguity? You'd have identically named methods with identical signatures.

于 2010-03-11T21:29:13.210 回答
2

相反,您可以将您的类型定义为:

public interface Y<A> : X<A,A>
{
}
于 2010-03-11T21:24:02.583 回答