如果我输入以下内容:
public Response GetArticles(string Filter = String.Empty)
{
//Body
}
Visual Studio 给我这个错误:
Default parameter value for 'Filter' must be a compile-time constant
如果我将 String.Empty
更改为经典的 ""
它是固定的。
但我仍然很好奇 String.Empty
及其行为有什么问题。
最佳答案
Why is String.Empty an invalid default parameter?
因为“'Filter' 的默认参数值必须是编译时常量”。并且 String.Empty
不是常量而只是 static readonly
。像 "Foo"
这样的字符串文字是作为实现细节的常量(我还没有找到文档)。
进一步阅读:Why isn't String.Empty a constant?
引用自 C# 语言规范的 10.4 常量:
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根据可选参数引用:
默认值必须是以下表达式类型之一:
- 常量表达式
- 形式为 new ValType() 的表达式,其中 ValType 是值类型,例如枚举或结构
- 一个 default(ValType) 形式的表达式,其中 ValType 是一个值类型。
我很惊讶您可以使用 new ValType()
,其中 ValType
是值类型或结构。我不知道您可以使用默认构造函数,例如 new DateTime()
但不能使用 new DateTime(2015,1,15)
。从我自己的回答中学到了一些新东西。
关于c# - 为什么 String.Empty 是无效的默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28043397/