Dart语法快速上手四《Dart2之操作符、循环、条件控制、异常

2018-09-29  本文已影响129人  凤天凌

Dart绝大多数的操作符和其他语言很相似,先列一张表


image.png
image.png

下面说一些不常见的

(emp as Person).firstName = 'Bob';
if (emp is Person) {
  // Type check
  emp.firstName = 'Bob';
}else if(emp is! Person){
.....
}
b ??= value; //当b为空的时候,value的值才会赋值给b
var collection = [0, 1, 2];
for (var x in collection) {
  print(x); // 0 1 2
}
var command = 'OPEN';
switch (command) {
  case 'OPEN':
    executeOpen();
    // ERROR: Missing break

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

还有一种用法是在进入一个case之后根据判断如果true我要执行A case 如果是false我要执行 B case,Dart也提供了支持,利用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;
}

断言

Dart里面支持断言,你必须确保判断是正确的才能通过这个断言,断言在生产环境中不起作用

// 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'));

异常

try {
  breedMoreLlamas();
} on OutOfLlamasException {
  // A specific exception
  buyMoreLlamas();
} on Exception catch (e) {
  // Anything else that is an exception
  print('Unknown exception: $e');
} catch (e) {
  // No specified type, handles all
  print('Something really unknown: $e');
}

on和catch的区别应该在于是否关心异常的实例

try {
  // ···
} on Exception catch (e) {
  print('Exception details:\n $e');
} catch (e, s) {
  print('Exception details:\n $e');
  print('Stack trace:\n $s');
}

你可以在catch里面多增加一个参数,第一个是异常的实例,第二个则是错误的堆栈信息

void misbehave() {
  try {
    dynamic foo = true;
    print(foo++); // Runtime error
  } catch (e) {
    print('misbehave() partially handled ${e.runtimeType}.');
    rethrow; // Allow callers to see the exception.
  }
}

void main() {
  try {
    misbehave();
  } catch (e) {
    print('main() finished handling ${e.runtimeType}.');
  }
}

By the way .Dart does support "Finally" keyWord too.

上一篇 下一篇

猜你喜欢

热点阅读