方法级联如何在 dart 中准确工作? [英] How do method cascades work exactly in dart?

查看:17
本文介绍了方法级联如何在 dart 中准确工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如飞镖文章所述:

.."语法调用方法(或 setter 或 getter)但丢弃结果,并返回原始接收器.

The ".." syntax invokes a method (or setter or getter) but discards the result, and returns the original receiver instead.

所以我认为这会起作用:

So I assumed that this would work:

myList..clear().addAll(otherList);

这给了我一个错误,我不能在 null 上调用 .addAll.

which gave me the error that I can't call .addAll on null.

很明显 ... 之前,所以 .addAll 已经在 result 上被调用>.clear().

So apparently . precedes .. so that .addAll has been invoked on the result of .clear().

我现在想我有两种可能来写这个:

I figure now that I have two possibilities to write this:

  1. myList..clear()..addAll(otherList);
  2. (myList..clear()).addAll(otherList);(如果我想得到.addAll()的结果.
  1. myList..clear()..addAll(otherList);
  2. (myList..clear()).addAll(otherList); (If I wanted to get the result of .addAll().

这是正确的吗?如果是,为什么决定给 . 优先?这似乎非常违反直觉.是否要避免这样的语法:myList(..clear().useResultOfClear()).addAll(otherList);?

Is this correct? If yes, why the decision to give . precedence? It seems very counterintuitive. Is it to avoid syntax like this: myList(..clear().useResultOfClear()).addAll(otherList);?

推荐答案

您可以阅读 Gilad Bracha 的文章:Dart 中的方法级联.在它的结尾,您会看到许多示例.

You can read the article from Gilad Bracha : Method Cascades in Dart. At its ends, you will see many examples.

另见 Lasse Nielsen 的这个回答运算符优先级 :

将.."视为不是真正的运算符,而更像是范围结构(如括号)会有所帮助.它创建一个从.."到下一个.."或第一个其他范围分隔符(;"、)"、}"或类似的范围)的新范围.

It helps to think of ".." as not really an operator, but more like a scoping construct (like parentheses). It creates a new scope from the ".." to either the next "..", or the first other scope delimiter (";", ")", "}" or similar).

基本上,a..b().c()(t){t.b().c();return t;}(a)

这篇关于方法级联如何在 dart 中准确工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆