Dart语言基础之流程控制

原文:https://www.dartlang.org/guides/language/language-tour

  • if and else
  • for loops
  • while and do-while loops
  • break and continue
  • switch and case
  • assert

switch

Dart 的switch支持 integer, string, 或 用==比较编译时常量. 被比较的实列的类必须相同 (不能是任何它的子类),并且不能重载 ==运算符.也支持 Enum 类型。

每个非空 casebreak 语句来结束. 结束 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 分支可以定义局部变量, 只在此分支内可见.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容