switch的使用方法:
-
switch(flag) /*flag是标识,当flag的值与哪个case 后面的值相等时,执行该条case下面的statements.*flag的取值类型可以是string/object*/ { case flag1: //这里的flag1/flag2必须是常量表达式,不允许使用变量 statements; break; //这里每条case里的break必须强制添加,否则编译通不过。 case flag2: statements: break; defalut: //这里的所有case与defalut的顺序都可以更改,并且不影响结果。 statements; break; }
- 如果两个case执行的statements相同可以将它们合并:
switch(flag) { case flag1: //在这里将case flag1与case flag2合并了。 case flag2: statements: break; defalut: statements; break; } - 每个case后面的值(即flag1/flag2等)不可以相同(名称不同,但是值相同的常量也不可以)。
using System;
namespace SwitchDemo
{
class Program
{
static void Main()
{
string flag = "third" ;
switch(flag)
{
case "first":
Console.WriteLine("I'm the first!");
break;
case "second":
Console.WriteLine("I'm the second!");
break;
case "third":
case "fourth":
Console.WriteLine("I'm the third or fourth!");
break;
default:
Console.WriteLine("I don't know!");
break;
}
Console.ReadKey();
}
}
}
深入理解switch语句的使用方法及案例解析
本文详细介绍了switch语句的基本语法、使用方法、注意事项,并通过实例展示了如何在不同场景下灵活运用switch语句进行条件判断。重点讨论了switch语句中case标签的合并使用、default情况的处理以及避免case标签重复的重要性。

被折叠的 条评论
为什么被折叠?



