c# - Switch/case 语句中的 String.Empty 生成编译器错误

标签 c# string compiler-errors switch-statement

如果 String.Empty"" 一样好,那么编译器怎么会在 case 语句中抛出 string.Empty ?在我看来,没有什么比 string.Empty 更稳定的了。有人知道吗?谢谢!

switch (filter)
            {
     case string.Empty:  // Compiler error "A constant value is expected"

                break;

                case "":  // It's Okay.
                    break;

            }

最佳答案

您可以这样尝试:

switch(filter ?? String.Empty)

string.Empty 是只读字段,而 "" 是编译时常量。您还可以在此处阅读有关代码项目的文章 String.Empty Internals

//The Empty constant holds the empty string value.
//We need to call the String constructor so that the compiler doesn't
//mark this as a literal.
//Marking this as a literal would mean that it doesn't show up as a field 
//which we can access from native.

public static readonly String Empty = ""; 

旁注:

当您在方法中提供默认参数值时 (C# 4.0),您也会看到此问题:

void myMethod(string filter = string.Empty){}

以上将导致编译时错误,因为默认值需要是常量。

关于c# - Switch/case 语句中的 String.Empty 生成编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32836504/

相关文章:

c# - 为什么需要声明

c# - 在 C# 中对 TextBox 实现输入限制的最佳方法是什么?

java - 用 Java 高效地解析和写入文件

python - 在 Python 中将字符串插入列表 (v. 3.4.2)

c++ - C++ [Codeblocks/Visual Studio] 中没有这样的目录或文件

c# - keyup 事件调用数据库函数并填充列表框

c# - Windows 窗体/WPF 太大,我该如何拆分?

string - 从字符串中删除重复的字符串

compiler-errors - C++从 'int'到 'int*'的无效转换

C++:为用户定义的类型进行转换