
4.3 switch 多分支语句
在开发中常见的一个问题是检测一个变量是否符合某种条件,如果不符合,则再用另一个值来检测它,依此类推。当然,这种问题可以使用if 语句来完成。
例如,使用if 语句检测变量是否符合某种条件。

在执行上述代码时,每一条if 语句都会进行判断,这样显得非常烦琐。为了简化这种编写代码的方式,C# 提供了switch 语句,将判断动作组织起来,以一种比较简单的方式实现 “多选一” 的逻辑。本节将对switch 语句进行详细讲解。
4.3.1 switch 语句

switch 语句是多分支条件判断语句,它根据参数的值使程序从多个分支中选择一个用于执行的分支,其基本语法如下。


switch 关键字后面的括号() 中的内容是要判断的参数,参数必须是sbyte、byte、short、ushort、int、uint、long、ulong、char、string、bool 或枚举类型中的一种。大括号{}中的代码是由多个case 子句组成的,每个case 关键字后面都有相应的语句块,这些语句块都是switch 语句可能执行的语句块。如果符合常量值,则case 后面的语句块就会被执行,语句块执行完毕后,执行break 语句,使程序跳出switch 语句;如果条件都不满足,则执行default 中的语句块。
学习笔记
(1)case 后的各常量值不可以相同,否则会出现错误。
(2)case 后面的语句块可以有多条语句,不必使用大括号括起来。
(3)case 语句和default 语句的顺序可以改变,这不会影响程序执行结果。
(4)一个switch 语句中只能有一个default 语句,而且default 语句可以省略。
switch 语句的执行流程图如图4.16 所示。

图4.16 switch 语句的执行流程图
示例5.查询高考录取分数线
使用switch 多分支语句实现查询高考录取分数线的功能。其中,民办本科为350 分、艺术类本科为290 分、体育类本科为280 分、二本为445 分、一本为555 分。代码如下。


查询高考录取分数线代码的运行结果如图4.17 所示。

图4.17 查询高考录取分数线代码的运行结果
学习笔记
在使用switch 语句时,常量表达式的值绝不可以是浮点类型的。例如,下面的代码就是不合法的。


在Visual Studio 2017 中运行上述代码时,将会出现如图4.18 所示的错误提示信息。

图4.18 判断参数为浮点类型时出现的错误提示信息
(2)在使用switch 语句时,每个case 语句或default 语句后面必须有一个break关键字,否则将会出现如图4.19 所示的错误提示信息。

图4.19 缺少break 关键字时出现的错误提示信息
4.3.2 switch 语句与if…else if…else 语句的区别

4.2.3节中讲到的if…else if…else 语句也可以处理多分支选择的情况,但它主要是对布尔表达式、关系表达式或逻辑表达式进行判断的,而switch 多分支语句主要对常量值进行判断。因此,在程序开发中,如果遇到多分支选择的情况,并且判断的条件不是关系表达式、逻辑表达式或浮点类型,就可以使用switch 语句代替if…else if…else 语句,这样执行效率会更高。