Meh*_*dad 5 .net c# generics ambiguity
可能重复:
通用方法和方法重载
说我喜欢上课
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 */ } }
}
Run Code Online (Sandbox Code Playgroud)
现在让我们说一些家伙决定使用它:
static string Test1<K>(K key) { return new SortedList<K>()[key]; }
Run Code Online (Sandbox Code Playgroud)
编译器将此调用解析为K key重载.
现在,与此相反
static string Test2(int key) { return new SortedList<int>()[key]; } // whoops
Run Code Online (Sandbox Code Playgroud)
编译器将此解析为int i重载.
现在,如果一个可怜的灵魂说Test1(0),如果他说,他会得到不同的结果Test2(0),即使乍一看身体看起来几乎相同.
更有趣的是,在任何情况下,编译器或运行时都不会检测到歧义并给出错误.
相反,运行时只是根据值是否是通用来改变其行为,这对于调用者来说可能是明显意外的.
为什么行为不一致?
或者,更好的是,为什么没有编译器(或运行时)错误,因为模糊不清?
您认为为什么黑客认为这是不一致的行为?这只是一点,你用“maybe-key”类型的 getter 覆盖索引 getter...
您认为预期的结果应该是什么?一个警告?开发人员需要检查您想要将哪些类型用于哪些泛型...它足够智能,可以检查方法“test1”将解决基于键的 getter,而 test2 仅解决基于索引的 getter...
你必须要么禁止“int”作为类型(例如带有类约束),要么在这里实现其他 getter 方法......
| 归档时间: |
|
| 查看次数: |
99 次 |
| 最近记录: |