问题描述
编辑1:我知道还有伸缩性之类的选择,这纯粹是教育性问题。
EDIT 1: I know there are alternatives such as telescoping, this was a purely educational question.
我知道这是真的,但是为什么会这样呢?似乎是这样的:
I know that this is true, but why must it be? It seems like with something like this:
public class Foo{
private int bar;
public void SetBar(int baz = ThatOtherClass.GetBaz(3)){
this.bar = baz;
}
}
编译器可以将方法更改为像这样的东西:
The compiler could change the method to something like this:
public void SetBar(int baz){
//if baz wasn't passed:
baz = ThatOtherClass.GetBaz(3);
this.bar = baz;
}
为什么不行,或者行得通,以及
Why wouldn't that work, or would it, and it's just a design decision?
推荐答案
因为规范是这样的:
带有默认参数的固定参数称为可选的
参数,而没有默认参数的固定参数是
必需参数。必需参数可能不会在形式参数列表中的
可选参数之后出现。 ref或out参数
不能具有默认参数。默认参数
中的表达式必须为以下值之一:
•常量表达式
•形式为new S()的表达式,其中S为值类型
• an expression of the form new S() where S is a value type
•形式为default(S)的表达式,其中S为值类型
• an expression of the form default(S) where S is a value type
关于语言设计师为什么选择这么做,我们只能猜测一下。但是,另一个规范提示了一个答案:
As to why the language designers chose to do this, that we can only guess at. However, another piece of the spec hints at an answer:
这篇关于为什么默认方法参数必须是C#中的编译时常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!