Zuz*_*zlx 5 c# string compiler-errors switch-statement
如果String.Empty一样好"",那么编译器如何在语句中抛出string.Empty case呢?string.Empty在我看来,没有比这更稳定的了.谁知道?谢谢!
switch (filter)
{
case string.Empty: // Compiler error "A constant value is expected"
break;
case "": // It's Okay.
break;
}
Run Code Online (Sandbox Code Playgroud)
您可以尝试这样:
switch(filter ?? String.Empty)
Run Code Online (Sandbox Code Playgroud)
string.Empty是只读字段,""而是编译时常量.您还可以在此处查看Code Project 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 = "";
Run Code Online (Sandbox Code Playgroud)
在旁注:
当您在方法(C#4.0)中提供默认参数值时,您还会看到此问题:
void myMethod(string filter = string.Empty){}
Run Code Online (Sandbox Code Playgroud)
以上将导致编译时错误,因为默认值需要是常量.