Dart 编程中的 switch 语句
Switch语句在我们希望基于特定条件运行特定代码的情况下帮助我们。确实,if-else条件在同一段代码中也对我们有帮助,但是switch语句降低了程序的复杂性,因为如果条件检查密集,那么在switch的情况下我们最终会得到更少的代码。
语法
switch(case){
case x:
//做点什么;
break;
case y:
//做点什么;
break;
default:
//做点什么;
}示例
考虑下面显示的例子-
void main() {
var name = "rahul";
switch(name){
case "mukul":
print("it is mukul");
break;
case "rahul":
print("it is rahul");
break;
default:
print("sorry ! default case");
}
}switch关键字后面的括号包含了我们想要与switch代码块中的不同case匹配的变量,当它匹配特定case时,将执行写在该case代码块中的语句并且代码将从switchcase中退出,因为我们在那里有一个break语句。
输出结果
it is rahul
应该注意的是,在每个switchcase中都有必要使用break关键字,因为如果我们没有的话编译器会出错。
示例
考虑下面显示的例子-
void main() {
var name = "rahul";
switch(name){
case "mukul":
print("it is mukul");
case "rahul":
print("it is rahul");
break;
default:
print("sorry ! default case");
}
}输出结果Error: Switch case may fall through to the next case. case "mukul": ^ Error: Compilation failed.
在大多数语言中,我们放置了break语句,以便我们可以跳到 下一个案例。我们也可以在dart中实现该场景。
示例
考虑下面显示的例子-
void main() {
var piece = 'knight';
switch(piece) {
case 'knight':
case 'bishop':
print('diagonal');
break;
}
}输出结果diagonal