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

标签 c# .net parameters optional-parameters compile-time

如果我输入以下内容:

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/

相关文章:

c# - 如何处理xamarin.forms中app.xaml.cs中的System.TypeLoadException?

c# - 将url参数字符串转换为路径的正则表达式

c# - 在更新外键字段之前释放 DataContext

c++ - 在 C++ 中将参数传递给 lambda

c++ - 如何在 Visual C++ 6.0 中使用命令行参数运行控制台应用程序?

c# - 在 Controller 类之外使用 Session

c# - Autopostback 仅在 ASP.NET 中首次运行?

javascript - 将表单数据 POST 中的数组发送到 PHP 端点

c# - 在 4.0 项目中引用 .net Framework 4.5.1 程序集

c# - 如何以编程方式按值选择下拉列表项