C# - Switch 语句
当您想针对三个或更多条件测试一个变量时,可以使用 switch
语句代替 if else
语句。在这里,您将学习 switch 语句以及如何在 C# 程序中高效地使用它。
以下是 switch 语句的通用语法。
switch(match expression/variable) { case constant-value: statement(s) to be executed; break; default: statement(s) to be executed; break; }
switch
语句以 switch
关键字开头,该关键字在括号 switch(匹配表达式)
中包含一个匹配表达式或变量。此匹配表达式或变量的结果将与花括号 内指定为 case 的条件进行测试。case 必须指定唯一的常量值,并以冒号
:
结尾。每个 case 都包含一个或多个要执行的语句。如果常量值与匹配表达式/变量的值相等,则执行该 case。switch
语句还可以包含一个可选的 default 标签。如果没有 case 执行,则执行 default 标签。break
、return
或 goto
关键字用于使程序控制退出 switch case。
以下示例演示了一个简单的 switch 语句。
int x = 10;
switch (x)
{
case 5:
Console.WriteLine("Value of x is 5");
break;
case 10:
Console.WriteLine("Value of x is 10");
break;
case 15:
Console.WriteLine("Value of x is 15");
break;
default:
Console.WriteLine("Unknown value");
break;
}
上面,switch(x)
语句包含一个变量 x
,其值将与每个 case 值进行匹配。上面的 switch
语句包含三个 case,常量值分别为 5、10 和 15。它还包含 default 标签,如果没有 case 值与 switch 变量/表达式匹配,则执行该标签。每个 case 在 :
之后开始,并包含一个要执行的语句。x
的值与第二个 case case 10:
匹配,因此输出将是 x 的值为 10
。
switch
语句还可以包含一个表达式,其结果将在运行时与每个 case 进行测试。
int x = 125;
switch (x % 2)
{
case 0:
Console.WriteLine($"{x} is an even value");
break;
case 1:
Console.WriteLine($"{x} is an odd Value");
break;
}
Switch Case
switch case 必须是唯一的常量值。它可以是 bool、char、string、integer、enum 或相应的可空类型。
考虑以下一个简单 switch 语句的示例。
string statementType = "switch";
switch (statementType)
{
case "if.else":
Console.WriteLine("if...else statement");
break;
case "ternary":
Console.WriteLine("Ternary operator");
break;
case "switch":
Console.WriteLine("switch statement");
break;
}
多个 case 可以组合起来执行相同的语句。
int x = 5;
switch (x)
{
case 1:
Console.WriteLine("x = 1");
break;
case 2:
Console.WriteLine("x = 2");
break;
case 4:
case 5:
Console.WriteLine("x = 4 or x = 5");
break;
default:
Console.WriteLine("x > 5");
break;
}
每个 case 必须通过使用 break
、return
、goto
语句或一些其他方式明确退出 case,确保程序控制退出 case 并且不能“落空”到 default case。
以下使用 return
关键字。
static void Main(string[] args)
{
int x = 125;
Console.Write( isOdd(x)? "Even value" : "Odd value");
}
static bool isOdd(int i, int j)
{
switch (x % 2)
{
case 0:
return true;
case 1:
return false;
default:
return false;
}
return false;
}
没有 break, return 或 goto
语句或具有相同常量值的 switch
case 将导致编译时错误。
int x = 1;
switch (x)
{
case 0:
Console.WriteLine($"{x} is even value");
break;
case 1:
Console.WriteLine($"{x} is odd Value");
break;
case 1: // Error - Control cannot fall through from one case label ('case 1:') to another
Console.WriteLine($"{x} is odd Value");
defaut:
Console.WriteLine($"{x} is odd Value");
break;
}
嵌套 Switch 语句
一个 switch
语句可以嵌套在另一个 switch
语句中。
int j = 5;
switch (j)
{
case 5:
Console.WriteLine(5);
switch (j - 1)
{
case 4:
Console.WriteLine(4);
switch (j - 2)
{
case 3:
Console.WriteLine(3);
break;
}
break;
}
break;
case 10:
Console.WriteLine(10);
break;
case 15:
Console.WriteLine(15);
break;
default:
Console.WriteLine(100);
break;
}
4
3