C#方法重载与PARAMS和自选方法、PARAMS

2023-09-04 02:39:17 作者:保持热忱

今天,我发现了一些奇怪的事情。我不知道为什么这样工作的:

Today I discovered something strange. I wonder why this works:

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);

Think about it: What is the result when you call ExampleMethod(3);

在我看来,这会导致一个未predictable结果。就我而言始终方法1被调用。但是,当我改变了方法1的签名,主要方法称为方法2(当然)。

In my opinion it leads to an unpredictable result. In my case always Method 1 was called. But as I changed the signature of Method 1, the Main Method called Method 2 (of course).

我没想到这样的行为,我期待一个AmbiguousReferenceException或者至少是一个编译器警告。

I did not expect such a behavior, I expected an "AmbiguousReferenceException" or at least a compiler warning.

推荐答案

我期望这是因为编译器知道 optionalstr 的默认值, optionalint ,因此能够使基于该上什么样的价值观使用的决定。它不知道该怎么设置为 INT [] optionalint 的值。由于编译器是更加肯定的,当你有可选参数干什么用的,它会调用该方法。

I'd expect this behaviour because the compiler knows the default values of optionalstr and optionalint and is therefore able to make a decision based on that on what values to use. It wouldn't know what to set as the value for int[] optionalint. Since the compiler is "more sure" of what to use when you have the optional parameters, it calls that method.

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

If you added an extra method like this

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

这将是所谓的,因为编译器会去,有没有第一可选参数的方法的方法。

this would be the method called because the compiler will go for the method that has no optional parameters first.

More详细说明的重载。