具有可选参数的冲突重载方法 [英] 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屋!