使用params和optionals的C#方法重载

时间:2013-06-30 12:14:19

标签: c# .net params

今天我发现了一些奇怪的东西。我想知道为什么会这样:

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(当然)。

我没想到会出现这样的行为,我预计会出现“AmbiguousReferenceException”或者至少是编译器警告。

1 个答案:

答案 0 :(得分:5)

我期望这种行为,因为编译器知道optionalstroptionalint的默认值,因此能够根据要使用的值来做出决定。它不知道要设置为int[] optionalint的值。由于编译器“更加确定”在使用可选参数时要使用的内容,因此它会调用该方法。

如果您添加了这样的额外方法

public static string ExampleMethod(int required)
{
    return "ExampleMethod 3";
}

这将是调用的方法,因为编译器将首先选择没有可选参数的方法。

关于重载解析的

More detailed explanation