C#使用String.IsNullOrEmpty进行切换

max*_*dbe 15 c# string switch-statement semantics

是否可以在C#中进行切换,检查值是空还是空而不是""但是String.Empty?我知道我可以这样做:

switch (text)
{
    case null:
    case "":
        break;
}
Run Code Online (Sandbox Code Playgroud)

还有更好的东西,因为我不想拥有大量的IF语句吗?

我试图替换:

if (String.IsNullOrEmpty(text))
    blah;
else if (text = "hi")
    blah
Run Code Online (Sandbox Code Playgroud)

Max*_*ler 30

我建议如下:

switch(text ?? String.Empty)
{
    case "":
        break;
    case "hi":
        break;
}
Run Code Online (Sandbox Code Playgroud)

那是你在找什么?


Mic*_*urr 23

您的示例switch声明有什么问题?

switch (text)
{
    case null:
    case "":
        foo();
        break;
    case "hi":
        bar();
        break;
}
Run Code Online (Sandbox Code Playgroud)

它起作用(并且由于某些原因让我感到惊讶 - 我认为它会在null案件中抱怨或崩溃)并且很清楚.

就此而言,你为什么担心String.Empty?我在这里遗漏了一些东西.


Jos*_*rke 6

怎么样

if (string.isNullOrEmpty(text))
{
   //blah
}
else
{
 switch (text)
 {
     case "hi":
 }
Run Code Online (Sandbox Code Playgroud)

}


rec*_*ive 5

文件String.Empty:

该字段的值是零长度字符串"".

我认为这意味着""和之间没有区别String.Empty.你为什么试图区分它们?