为什么.Net 允许诸如此类的模棱两可的方法

Why does .Net allow ambiguous methods such as these

目前我使用的是 .Net 3.5,所以请告诉我它是否已在更高版本中修复。

目前我有 2 个具有以下签名的方法:

void Method1(string, string)
void Method1(string, params string[])

如果我打这样的电话

Method1("test1", "test2")

编译器如何知道调用哪个方法?为什么 .Net 允许这样做?

我假设在 IL 中,生成的代码是不同的,因此是允许的,但它不应该,因为您可能会得到意想不到的结果。允许这样做有充分的理由吗?

提前致谢。

how does the compiler know which method to call?

它遵循 C# 语言规范中列出的重载解析规则。特别是在第 7.5.3.2 节中(查看 C# 4 规范,但我相信 C# 5 在这里具有相同的编号)-“更好的函数成员”:

In case the parameter type seqquences are equivalent [...] the following tie-breaking ruls are applied, in order, to determine the better function member:

  • ...
  • Otherwise, if MP is applicable in its normal form and MQ has a params array and is applicable only in its expanded form, then MP is better than MQ.

因此在您的示例中,它将调用第一个重载。

Why does .Net allow this?

因为它在各种情况下都很有用(例如 Console.WriteLine 一开始)。

I assume that in the IL, the resulting code is different and therefore allowed, but it shouldn't be, because you can get unexpected results.

如果您不希望 C# 编译器遵循其规范,您只会得到意想不到的结果。在那种情况下,几乎任何行为都可能出乎意料。