gpt4 book ai didi

parameters - 具有可选参数的冲突重载方法

转载 作者:行者123 更新时间:2023-12-03 10:50:19 24 4
gpt4 key购买 nike

我有两种重载方法,一种带有可选参数。

void foo(string a)  { }  
void foo(string a, int b = 0) { }

现在我打电话:
 foo("abc");

有趣的是,第一个重载被调用。
为什么不将可选值设置为零的第二个重载?

老实说,我原以为编译器会带来错误,至少是警告,以避免无意中执行错误的方法。

这种行为的原因是什么?为什么 C# 团队这样定义它?

最佳答案

来自 MSDN :

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.

关于parameters - 具有可选参数的冲突重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2674417/

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