C#_switch语句-基本语法

switch语句-基本语法

switch语句类似于if语句,switch可以用来将测试变量跟多个值进行比较。switch的语法结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
switch(<testvar>){
case<comparisonvar1>:
<code to execute if<testvar>==<comparisionvar1>>
break;
case<comparisonvar2>:
<code to execute if<testvar>==<comparisionvar2>>
break;
...
default://如果上面的都不成立,则运行默认的代码
<code to execute if<testvar>!=<comparisionvals>>
break;
}
<testvar>这里不管直接放一个字面值还是变量,它的类型是数值类型跟char类型

switch语句-练习

定义一个int类型存储游戏状态
0代表开始界面 1战斗中 2暂停 3游戏胜利 4游戏失败
使用switch判断游戏状态,并输出游戏状态

实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _24
{
class Program
{
static void Main(string[] args)
{
int str = 3;
switch (str)
{
case 0:
Console.WriteLine("开始界面");
break;
case 1:
Console.WriteLine("战斗中");
break;
case 2:
Console.WriteLine("暂停");
break;
case 3:
Console.WriteLine("游戏胜利");
break;
case 4:
case 5: //当值是4或者5的时候执行下面那句
Console.WriteLine("游戏失败");
break;
default:
Console.WriteLine("当前str超出了游戏状态的取值范围");
break;
}
Console.ReadKey();
}
}
}