【问题标题】:How do I reference "this" while method cascading in Dart?在 Dart 中级联方法时如何引用“this”?
【发布时间】:2014-03-06 16:41:20
【问题描述】:

我想在 Dart 中级联方法时引用“this”(方法所有者)。

// NG code, but what I want.
paragraph.append( getButton()
    ..text = "Button A"
    ..onClick.listen((e) {
      print (this.text + " has been has clicked"); // <= Error. Fail to reference "button.text".
    }));

我知道我可以通过将其拆分为多行来编写这样的代码。

// OK code, I think this is verbose.
var button;
button = getButton()
    ..text = "Button A"
    ..onClick.listen((e) {
      print (button.text + " has been clicked");
    }));
paragraph.append( button);

由于无法引用级联源对象,我在很多情况下都无法编写更短的代码。有没有更好的方法级联方法?

【问题讨论】:

    标签: dart method-cascades


    【解决方案1】:

    你不能随意使用this

    您可以使用以下代码简化第二个代码 sn-p:

    var button = getButton();
    paragraph.append(button
        ..text = "Button A"
        ..onClick.listen((e) {
          print (button.text + " has been has clicked");
        }));
    

    【讨论】:

    • 进一步扩展,Dart 是词法范围的,所以“this”永远不会指代您正在创建的按钮。它指的是整个方法在其中运行的对象。这可能没有文本方法。通过更改为“this.toString()”,您可以很容易地看到这一点
    猜你喜欢
    • 2013-06-06
    • 1970-01-01
    • 2020-04-09
    • 2015-07-21
    • 2020-10-30
    • 1970-01-01
    • 2012-12-06
    • 1970-01-01
    • 2021-05-14
    相关资源
    最近更新 更多