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