今天我发现了一些奇怪的事情。我想知道为什么这有效:
static void Main(string[] args)
{
Console.WriteLine(ExampleMethod(3));
Console.ReadKey();
}
public static string ExampleMethod(int required, params int[] optionalint)
{
return "ExampleMethod 2";
}
public static string ExampleMethod(int required, string optionalstr = "default string", int optionalint = 10)
{
return "ExampleMethod 1";
}
想一想:调用ExampleMethod(3);的结果是什么?
在我看来,这会导致不可预测的结果。就我而言,始终调用方法 1。但当我更改了方法 1 的签名时,主方法调用了方法 2(当然)。
我没想到会出现这样的行为,我预计会出现“AmbigouslyReferenceException”或至少是编译器警告。
我期望这种行为,因为编译器知道默认值optionalstr
and optionalint
因此能够根据要使用的值做出决定。它不知道要设置什么值int[] optionalint
。由于当您有可选参数时,编译器“更确定”要使用什么,因此它会调用该方法。
如果你添加了这样的额外方法
public static string ExampleMethod(int required)
{
return "ExampleMethod 3";
}
这将是被调用的方法,因为编译器将首先选择没有可选参数的方法。
更详细的解释 https://stackoverflow.com/questions/3190248/how-does-c-sharp-choose-with-ambiguity-and-params关于过载解析。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)