使用可选参数冲突重载方法 [英] Conflicting overloaded methods with optional parameters
问题描述
我有两个重载方法,一个有可选参数。
I have two overloaded methods, one with an optional parameter.
void foo(string a) { }
void foo(string a, int b = 0) { }
现在我调用:
foo("abc");
有趣的是,第一个重载被调用。
为什么不是第二个重载的可选值设置为零?
interestingly the first overload is called. why not the second overload with optional value set to zero?
说实话,我希望编译器带来一个错误,至少一个警告以避免无意的执行错误的方法。
To be honest, I would have expect the compiler to bring an error, at least a warning to avoid unintentional execution of the wrong method.
这种行为的原因是什么?为什么C#团队会这样定义?
What's the reason for this behaviour? Why did the C# team define it that way?
推荐答案
从 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.
这篇关于使用可选参数冲突重载方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!