Dart Primer 004 : 操作符与流程控制

1 min read May 17, 2018

Dart Primer 004 : 操作符与流程控制

Table of Content

Dart 语言整体上与 C++Java 类似, 当然也有一些细节需要注意区分。

操作符

取整

操作符 ~/ 应该是很少见的一种写法:

int a = 3
int b = 2
print(a ~/ b); // 输出 1

级联

当你要对同一个对象进行一系列操作调用时, 使用 .. 操作符连接:

class Person {
    String name;
    String country;
    void setCountry(String country) {
      this.country = country;
    }
    String toString() => 'Name: $name\nCountry: $country';
}

void main() {
  Person p = new Person();
  p ..name = 'Ezra'
    ..setCountry('China');
  print(p);
}

流程控制

if

if 语句与大多数语言基本一致, 判断的条件为逻辑布尔值。

if (i < 0) {
  print('i < 0');
} else if(i == 0) {
  print('i = 0');
} else {
  print('i > 0');
}

在检查模式下, 对非布尔值进行判断会报错, 生产模式下则会当做 false 处理。

你可以通过 == null 来判断一个非布尔值是否为 null

for

for 循环也与大多数语言基本一致。

for (int i = 0; i < 3; i++) {
  print(i);
}

对于容器, 可以使用 forEachfor-in:

var collection = [0, 1, 2];

collection.forEach((x) => print(x)); // forEach 的参数为 Function

for (var x in collection) {
  print(x);
}

while/do-while

while (boolean) {
  // ...
}

do {
  // ...
} while (boolean)

switch-case

switch 的参数可以是数值或字符串:

var command = 'OPEN';

switch (command) {
  case 'CLOSED':
    // ...
    break;
  case 'OPEN':
    // ...
    break;
  default:
    print('Default');
}

break/fall-through

当一个 case 语句后没有代码, 则可以省略 break, 自动 fall-through 到下一个 case; 但如果 case 语句后有任何代码, 必须添加 break

continue

当一个 case 后有代码需要执行, 你仍旧希望 fall-through 到其他 case 时, 使用 continue LABEL 语法:

var command = 'CLOSED';

switch (command) {
  case 'CLOSED':
    print('CLOSED');
    continue nowClosed; // 继续执行 nowClosed 位置后的 case
  case 'OPEN':
    print('OPEN');
    break;
  nowClosed: // 此标签后的 NOW_CLOSED case 将通过前面 continue nowClosed 继续执行
  case 'NOW_CLOSED':
    print('NOW_CLOSED');
    break;
}

try-catch-finally

与大多数语言不同的是, Dart 中除了 ExceptionError 外, 还可以抛出非空对象作为异常。

throw new ExpectException('值必须大于 0!');
throw '值必须大于 0!';

你可以抛出多种类型的异常, 将被第一个捕获的 catch 进行处理。如果 catch 语句没有指定要接收的异常类型, 则会接收所有类型。

try {
    throw 'This an Exception!';
} on Exception catch(e) { // 指定类型
  print('Unknown exception: $e');
} catch(e) { // 不指定类型
  print('Unknown type: $e');
}

在此基础上, 你还可以添加 finally 语句, 不论异常是否产生都会被执行:

try {
    throw 'This an Exception!';
} catch(e) {
  print('Catch Exception: $e');
} finally {
  print('Close');
}
Picsew | Ezra