使用可选参数重载方法

Method Overloading with Optional Parameter

我有一个 class 有两个重载方法。

Class A
{
    public string x(string a, string b)
    {
        return "hello" + a + b;
    }

    public string x(string a, string b, string c = "bye")
    {
        return c + a + b;
    }
}

如果我使用两个参数从另一个 class 调用方法 x,那么将执行哪个方法,为什么?即,

string result = new A().x("Fname", "Lname");

我已经在我的控制台应用程序中对此进行了测试,并且执行了带有 2 个参数的方法。有人可以解释一下吗?

命名参数和可选参数的使用会影响重载决策:

If two candidates are judged to be equally good, preference goes to a candidate that does not have optional parameters for which arguments were omitted in the call. This is a consequence of a general preference in overload resolution for candidates that have fewer parameters.

参考:MSDN


暗示上面带有2个参数的规则方法string x(string a,string b)将被调用。

注意:如果两个重载方法都有可选参数,那么编译器会给出编译时歧义错误。

如果您调用带有两个参数的方法,它会使用带有两个参数的方法。如果你用三个调用一个,它会使用另一个。

它将始终执行首先与参数完全匹配的方法,在您的情况下它将执行:

可选参数方法优先级低于参数个数准确的函数

public string x(string a, string b);