编辑 1:我知道有其他选择,例如伸缩,这纯粹是一个教育问题。
我知道这是真的,但为什么一定是这样呢?看起来像这样:
public class Foo{
private int bar;
public void SetBar(int baz = ThatOtherClass.GetBaz(3)){
this.bar = baz;
}
}
编译器可以将方法更改为如下所示:
public void SetBar(int baz){
//if baz wasn't passed:
baz = ThatOtherClass.GetBaz(3);
this.bar = baz;
}
为什么那行不通,或者行不通,这只是一个设计决定?
因为规范是这样说的:
A fixed-parameter with a default-argument is known as an optional
parameter, whereas a fixed-parameter without a default-argument is a
required parameter. A required parameter may not appear after an
optional parameter in a formal-parameter-list. A ref or out parameter
cannot have a default-argument. The expression in a default-argument
must be one of the following:
• a constant-expression
• an expression of the form new S() where S is a value type
• an expression of the form default(S) where S is a value type
至于为什么语言设计者选择这样做,我们只能猜测。然而,规范的另一部分暗示了答案:
When arguments are omitted from a function member with corresponding
optional parameters, the default arguments of the function member
declaration are implicitly passed. Because these are always constant,
their evaluation will not impact the evaluation order of the remaining
arguments.