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

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


Dart语法快速上手四《Dart2之操作符、循环、条件控制、异常》_第1张图片
image.png

Dart语法快速上手四《Dart2之操作符、循环、条件控制、异常》_第2张图片
image.png

下面说一些不常见的

  • as 强转操作符
(emp as Person).firstName = 'Bob';
  • is / is! 判断对象类型操作符
if (emp is Person) {
  // Type check
  emp.firstName = 'Bob';
}else if(emp is! Person){
.....
}
  • 空赋值操作符
b ??= value; //当b为空的时候,value的值才会赋值给b
  • ?. 类似于Kotlin的非空判断,a?.b 在a不为空的时候执行a.b

  • for in循环,除了常规的for循环以外,还支持for in 循环

var collection = [0, 1, 2];
for (var x in collection) {
  print(x); // 0 1 2
}
  • Switch case 除了正常的比较也是支持枚举类型的
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'));

异常

  • throw Exception
    void distanceTo(Point other) => throw UnimplementedError();//这是抛出异常的方法

  • catch

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里面多增加一个参数,第一个是异常的实例,第二个则是错误的堆栈信息

  • rethrow
    Dart允许你在捕获异常的同时进行传播,如果你需要这样做,请使用rethrow关键字
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.

你可能感兴趣的:(Dart语法快速上手四《Dart2之操作符、循环、条件控制、异常》)