String.Empty in Switch/case 语句生成编译器错误

String.Empty in Switch/case statement generate a compiler error

如果 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){}

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

原因是:您不能使用 readonly 值以防万一:请考虑以下情况:

public string MyProperty { get; } // is a read-only property of my class
switch (filter)
{
    case MyProperty:  // wont compile this since it is read only
    break;
          // rest of statements in Switch
}

如你所说 string.Empty 等同于 "",这里我可以用相同的 switch 语句示例来证明这一点:

string filter = string.Empty;
switch (filter)
{
   case "":  // It's Okay.
   break;
    //rest of  statements in Switch
}

如果它是只读的,那么它不允许 string.Empty 的唯一原因是,开关在它的情况下不允许只读值。