为什么String.Empty是无效的默认参数? [英] Why is String.Empty an invalid default parameter?

查看:47
本文介绍了为什么String.Empty是无效的默认参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我输入以下内容:

public Response GetArticles(string Filter = String.Empty)
{
    //Body
}

Visual Studio给我这个错误:

Visual Studio gives me this error:

过滤器"的默认参数值必须为编译时常量

如果我将 String.Empty 更改为经典的" ,则它是固定的.

If I change the String.Empty to the classic "" it is fixed.

但是我仍然对 String.Empty 的问题及其行为感到好奇.

But I'm still curious about what is wrong with the String.Empty and its behavior.

推荐答案

为什么String.Empty是无效的默认参数?

Why is String.Empty an invalid default parameter?

因为过滤器"的默认参数值必须是编译时常量".并且 String.Empty 不是常量,而只是 static只读.诸如"Foo" 之类的字符串文字是作为实现细节的常量(我尚未找到文档).

Because "Default parameter value for 'Filter' must be a compile-time constant". And String.Empty is not a constant but only static readonly. String literals like "Foo" are constants as implementation detail(i haven't found documentation).

进一步阅读:为什么不是String.Empty是一个常量?

引用C#语言规范的10.4常量:

Quote from 10.4 Constants of the C# language specification:

readonly关键字与const关键字不同.const字段只能在字段的声明中进行初始化.只读字段可以在声明中或在构造函数.因此,只读字段可以具有不同的值取决于使用的构造函数.另外,虽然const字段是编译时常量,只读字段可用于运行时常数

The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants

以下是根据可选参数的 MSDN 引号:

Here is the MSDN quote according to optional parameters:

默认值必须是以下类型的表达式之一:

A default value must be one of the following types of expressions:

  • 一个常量表达式
  • 形式为new ValType()的表达式,其中ValType是值类型,例如枚举或结构
  • default(ValType)形式的表达式,其中ValType是值类型.

我很惊讶您可以使用 new ValType(),其中 ValType 是值类型或结构.我不知道您可以使用默认的构造函数,例如 new DateTime(),但不能使用 new DateTime(2015,1,15).从我自己的答案中学到了一些新知识.

I'm suprised that you can use new ValType(), where ValType is a value type or struct. I didn't know that you can use the default constructor like new DateTime() but not new DateTime(2015,1,15). Learned something new from my own answer.

这篇关于为什么String.Empty是无效的默认参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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