为什么默认方法参数必须是C#中的编译时常量 [英] Why must default method parameters be compile-time constants in C#

查看:709
本文介绍了为什么默认方法参数必须是C#中的编译时常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑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参数
不能具有默认参数。默认参数
中的表达式必须为以下值之一:

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:

•常量表达式

•形式为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:


当函数成员中省略了带有相应
可选参数的参数时,则隐式传递函数成员
声明的默认参数。由于这些参数始终是常数,因此
的求值不会影响其余
参数的求值顺序。

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#中的编译时常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆