從C# 7.0開始,switch語句也支持字符串類型的判斷。在switch語句中可以使用字符串作為case標(biāo)簽,如下所示:
string fruit = "apple";
switch (fruit)
{
case "apple":
Console.WriteLine("This is an apple.");
break;
case "banana":
Console.WriteLine("This is a banana.");
break;
default:
Console.WriteLine("Unknown fruit.");
break;
}
上面的代碼中,switch語句根據(jù)字符串變量fruit
的值來執(zhí)行不同的case塊。如果fruit
的值是"apple",則會(huì)輸出"This is an apple.“;如果是"banana”,則會(huì)輸出"This is a banana.“;否則會(huì)輸出"Unknown fruit.”。