美文网首页
Dart(2.2) - 流程控制语句

Dart(2.2) - 流程控制语句

作者: Longshihua | 来源:发表于2019-04-30 08:57 被阅读0次

流程控制语句

可以使用下面的语句来控制Dart代码的流程:

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

使用try-catchthrow还能影响控制流程的 跳转,详情请参考Exceptions.

If and else

Dart支持if语句以及可选的`else1,例如下面的示例。 另参考conditional expressions

if (isRaining()) {
  you.bringRainCoat();
} else if (isSnowing()) {
  you.wearJacket();
} else {
  car.putTopDown();
}

注意,Dart中和JavaScript对待 true 的区别。 参考 Booleans

For loops

可以使用标准的for循环:

var message = StringBuffer('Dart is fun');
for (var i = 0; i < 5; i++) {
  message.write('!');
}

Dartfor循环中的闭包能获取循环变量的值,避免了像Javascript中的常见陷阱,如下例

var callbacks = [];
for (var i = 0; i < 2; i++) {
  callbacks.add(() => print(i));
}
callbacks.forEach((c) => c());

正如我们所期待的,输出结果分别是0和1,但相反的情况可以在Javascript中见到,输出分别为2和2。

如果要遍历的对象实现了Iterable接口,则可以使用 forEach() 方法。如果没必要当前遍历的索引,则使用 forEach() 方法 是个非常好的选择:

candidates.forEach((candidate) => candidate.interview());

List 和 Set 等实现了 Iterable 接口的类还支持 for-in 形式的 iteration

var collection = [0, 1, 2];
for (var x in collection) {
  print(x); // 0 1 2
}

While and do-while

while循环在执行循环之前先判断条件是否满足:

while (!isDone()) {
  doSomething();
}

do-while循环是先执行循环代码再判断条件:

do {
  printLine();
} while (!atEndOfPage());

Break and continue

使用break来终止循环:

while (true) {
  if (shutDownRequested()) break;
  processIncomingRequests();
}

使用continue来开始下一次循环:

for (int i = 0; i < candidates.length; i++) {
  var candidate = candidates[i];
  if (candidate.yearsExperience < 5) {
    continue;
  }
  candidate.interview();
}

上面的代码在实现 Iterable 接口对象上可以使用下面的写法:

candidates
    .where((c) => c.yearsExperience >= 5)
    .forEach((c) => c.interview());

Switch and case

Dart中的 Switch 语句使用 == 比较 integerstring、或者编译时常量。 比较的对象必须都是同一个类的实例(并且不是 其之类),class必须没有覆写 == 操作符。Enumerated types非常适合 在 switch 语句中使用。

注意:Dart 中的Switch语句仅适用于有限的情况, 例如在解释器或者扫描器中使用。

每个非空的case语句都必须有一个break语句。 另外还可以通过 continuethrow或者return来结束非空case语句。

当没有case语句匹配的时候,可以使用default语句来匹配这种默认情况。

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();
}

下面的示例代码在case中省略了break语句, 编译的时候将会出现一个错误:

var command = 'OPEN';
switch (command) {
  case 'OPEN':
    executeOpen();
    // ERROR: Missing break

  case 'CLOSED':
    executeClosed();
    break;
}

然而,Dart支持空的case分句,并允许使用从一个case到另一个case的贯穿形式:

var command = 'CLOSED';
switch (command) {
  case 'CLOSED': // Empty case falls through.
  case 'NOW_CLOSED':
    // Runs for both CLOSED and NOW_CLOSED.
    executeNowClosed();
    break;
}

如果你需要实现这种继续到下一个case语句中继续执行,则可以 使用continue 语句跳转到对应的标签(label)处继续执行:

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 语句可以有局部变量局部变量,只有在这个语句内可见。

Assert

如果一个布尔条件值为false,使用assert语句来中断正常执行的代码。你可以在本教程中找到一些assert语句的样例。这里有一些例子:

// Make sure the variable has a non-null value.
assert(text != null);

// Make sure the value is less than 100.
assert(number < 100);

// Make sure this is an https URL.
assert(urlString.startsWith('https'));

提示:Assert语句仅仅只能在调试模式下使用,在生产模式下没有任何作用。

为了给assert添加相关信息,可以添加字符串作为第二个参数

assert(urlString.startsWith('https'),
    'URL ($urlString) should start with "https".');

assert语句后面的括号中,第一个参数可以加入任何表示布尔值或者函数的表达式。如果表达式的值或者函数返回值true,则assert语句成功并继续执行代码。如果值为false,则assert语句失败并抛出一个异常 (an AssertionError)。

参考

Dart

相关文章

网友评论

      本文标题:Dart(2.2) - 流程控制语句

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