美文网首页
Dart语言基础之流程控制

Dart语言基础之流程控制

作者: 星空下奔跑 | 来源:发表于2019-04-05 00:13 被阅读0次

原文: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 分支可以定义局部变量, 只在此分支内可见.

相关文章

网友评论

      本文标题:Dart语言基础之流程控制

      本文链接:https://www.haomeiwen.com/subject/mogciqtx.html