gpt4 book ai didi

c# - 使用可选参数重载方法

转载 作者:IT王子 更新时间:2023-10-29 04:24:26 26 4
gpt4 key购买 nike

我有一个带有两个重载方法的类。

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

如果我使用两个参数从另一个类调用方法 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) 将被调用。

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

关于c# - 使用可选参数重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39219180/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com