- if and else
- for loops
- while and do-while loops
- break and continue
- switch and case
- assert
switch
Dart 的switch支持 integer, string, 或 用==比较编译时常量. 被比较的实列的类必须相同 (不能是任何它的子类),并且不能重载 ==运算符.也支持 Enum 类型。
每个非空 case 以break 语句来结束. 结束 case 的其他方法还有 continue, throw, 或者 return 语句.
var command = 'OPEN';
switch (command) {
case 'CLOSED':
executeClosed();
break;
case 'PENDING':
executePending();
break;
case 'APPROVED':
executeApproved();
break;
case 'DENIED':
executeDenied();
break;
case 'OPEN':
executeOpen();
break;
default:
executeUnknown();
}
省略号break会报错:
var command = 'OPEN';
switch (command) {
case 'OPEN':
executeOpen();
// ERROR: Missing break
case 'CLOSED':
executeClosed();
break;
}
Dart支持空 case分支:
var command = 'CLOSED';
switch (command) {
case 'CLOSED': // Empty case falls through.
case 'NOW_CLOSED':
// Runs for both CLOSED and NOW_CLOSED.
executeNowClosed();
break;
}
continue :
var command = 'CLOSED';
switch (command) {
case 'CLOSED':
executeClosed();
continue nowClosed;
// Continues executing at the nowClosed label.
nowClosed:
case 'NOW_CLOSED':
// Runs for both CLOSED and NOW_CLOSED.
executeNowClosed();
break;
}
case 分支可以定义局部变量, 只在此分支内可见.











网友评论