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

时间:2015-09-29 05:47:02

标签: 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;

            }

2 个答案:

答案 0 :(得分:6)

您可以尝试这样:

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

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

答案 1 :(得分:3)

原因是:您无法使用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的唯一原因是,在这种情况下,switch不会允许只读值。