gpt4 book ai didi

c# - 为什么泛型的歧义不一致,而不是引发错误?

转载 作者:太空狗 更新时间:2023-10-29 23:52:10 25 4
gpt4 key购买 nike

<分区>

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 看起来很漂亮乍一看非常相似。

更有趣的是,在任何情况下,编译器或运行时都不会检测到歧义并给出错误。
相反,运行时只是根据值是否为泛型改变其行为,这对于调用者来说显然是出乎意料的。

为什么行为不一致?
或者,更好的是,为什么没有编译器(或运行时)错误因为歧义?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com