<分区>
Possible Duplicate:
Generic methods and method overloading
假设我有一个类
class SortedList<K>
{
public string this[int i] { get { return "a"; /* dummy sample code */ } }
public string this[K key] { get { return "b"; /* dummy sample code */ } }
}
现在假设某个人决定使用它:
static string Test1<K>(K key) { return new SortedList<K>()[key]; }
编译器将此调用解析为 K 键
重载。
现在,对比一下这句话
static string Test2(int key) { return new SortedList<int>()[key]; } // whoops
编译器将其解析为 int i
重载。
现在,如果某个可怜的人说 Test1(0)
,他会得到与他说 Test2(0)
不同的结果,即使 body 看起来很漂亮乍一看非常相似。
更有趣的是,在任何情况下,编译器或运行时都不会检测到歧义并给出错误。
相反,运行时只是根据值是否为泛型改变其行为,这对于调用者来说显然是出乎意料的。
为什么行为不一致?
或者,更好的是,为什么没有编译器(或运行时)错误因为歧义?