dart 学习 之 级联

级联

要对同一对象执行一系列操作,请使用级联(...)。我们都看到过这样的表达式:

myObject.someMethod()
它在 myObject 上调用 someMethod 方法,而表达式的结果是 someMethod 的返回值。

下面是一个使用级连语法的相同表达式:

myObject..someMethod()

虽然它仍然在 myObject 上调用了 someMethod,但表达式的结果却不是该方法返回值,而是是 myObject 对象的引用!使用级联,你可以将需要单独操作的语句链接在一起。例如,下方的代码使用了空判断调用符 (?.) 在 button 不为 null 时获取属性:

var button = querySelector('#confirm');
button?.text = 'Confirm';
button?.classes.add('important');
button?.onClick.listen((e) => window.alert('Confirmed!'));
button?.scrollIntoView();

现在你可以在第一个级联位置,使用 空判断 级联操作符 (?..),它可以确保级联操作均在实例不为 null 时执行。使用空判断级联后,你也不再需要 button 变量了:

querySelector('#confirm')
  ?..text = 'Confirm'
  ..classes.add('important')
  ..onClick.listen((e) => window.alert('Confirmed!'))
  ..scrollIntoView();

Q:使用级联创建一个语句,分别将 BigObject 的 anInt 属性设为 1、aString 属性设为 String!、aList 属性设置为 [3.0] 然后调用 allDone()。

class BigObject {
  int anInt = 0;
  String aString = '';
  List<double> aList = [];
  bool _done = false;
  
  void allDone() {
    _done = true;
  }
}

BigObject fillBigObject(BigObject obj) {
  // Create a single statement that will update and return obj:
  return TODO('obj..');
}

A:

class BigObject {
int anInt = 0;
String aString = '';
List<double> aList = [];
bool _done = false;

void allDone() {
  _done = true;
}
}

BigObject fillBigObject(BigObject obj) {
return obj
  ..anInt = 1
  ..aString = 'String!'
  ..aList.add(3)
  ..allDone();
}
相关推荐
GFCGUO13 分钟前
ubuntu18.04运行OpenPCDet出现的问题
linux·python·学习·ubuntu·conda·pip
丝丝不是土豆丝2 小时前
学习 CSS 新的属性 conic-gradient 实现环形进度条
学习
S hh2 小时前
【Linux】进程地址空间
java·linux·运维·服务器·学习
万叶学编程2 小时前
Day02-JavaScript-Vue
前端·javascript·vue.js
wusam2 小时前
螺蛳壳里做道场:老破机搭建的私人数据中心---Centos下Docker学习04(环境准备)
学习·docker·centos
攸攸太上2 小时前
Spring Gateway学习
java·后端·学习·spring·微服务·gateway
Geek之路3 小时前
QT系统学习篇(1)
开发语言·qt·学习
IFTICing3 小时前
【文献阅读】Attention Bottlenecks for Multimodal Fusion
人工智能·pytorch·python·神经网络·学习·模态融合
新手unity自用笔记4 小时前
项目-坦克大战学习-子弹的移动与销毁
笔记·学习·c#