【问题标题】:String.Empty in Switch/case statement generate a compiler errorSwitch/case 语句中的 String.Empty 生成编译器错误
【发布时间】:2015-09-29 05:47:02
【问题描述】:

如果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;

            }

【问题讨论】:

标签: c# string compiler-errors switch-statement


【解决方案1】:

你可以这样尝试:

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

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

【讨论】:

  • 谢谢拉胡尔。但我只是想知道为什么我们不能使用 string.Empty。这对我来说有点奇怪。
  • @Zuzlx:- 据我所知string.Empty 是一个只读字段,而"" 是一个编译时间常数。
  • 有道理。再次感谢。我们可以发现火星上有水,但是我们不能用string.Empty测试""悲伤的事态
【解决方案2】:

原因是:不能使用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 在它是只读的情况下的唯一原因是,开关在它的情况下不允许只读值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多