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

Dart绝大多数的操作符和其他语言很相似,先列一张表
image.png
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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值