c# - 为什么默认方法参数必须是 C# 中的编译时常量

标签 c# default compile-time-constant

<分区>

编辑 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.

关于c# - 为什么默认方法参数必须是 C# 中的编译时常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26242946/

相关文章:

html - 如何让表单默认为浏览器样式

Clojure 编译时常量

java - 编译时间常数

c# - 从 ViewMode/Viewl MVVM 发出保存模型

Java Runnable 的 C# 版本? (委托(delegate)?)

javascript - Datepicker 将今天设置为默认日期

symfony - 为所有 Symfony 表单类型设置默认值

c++ - 如何定义作为不可实例化类的静态成员的数组的大小?

c# - 为什么此代码会生成 NotSupportedException?

c# - 无法将 'Emgu.CV.Matrix<double>'类型隐式转换为'double