【问题标题】:How do I use `this` in constructors?如何在构造函数中使用 `this`?
【发布时间】:2020-01-21 19:22:49
【问题描述】:

在 python 中,如果我在对象上调用方法,则将对对象本身的引用放入函数中。我想在 dart 中有类似的行为,但我不知道如何使用 self 变量获得与 python 中相同的行为。 我基本上想实现这样的行为:

class Parent:
    def __init__(self):
        self.child = Child(self)

class Child:
    def __init__(self, parent):
        self.parent = parent

在 dart 中,我希望它看起来像这样:

class Parent {
  final Child child;

  Parent() : this.child = Child(this);
}

class Child {
  final Parent parent;

  Child(parent) : this.parent = parent;
}

但是将 this 关键字放在 dart 的括号中会导致错误。 错误信息是:

Error compiling to JavaScript:
main.dart:4:33:
Error: Can't access 'this' in a field initializer.
  Parent() : this.child = Child(this);
                                ^^^^
Error: Compilation failed.

如何在 dart 中实现 python 代码中演示的行为?

【问题讨论】:

  • "把this关键字放到dart的括号里会报错"什么错误?请显示完整的错误消息。

标签: python flutter dart


【解决方案1】:

您不能在构造函数头部和初始化列表中访问this(详细了解here)。

如果你想这样做,你必须在构造函数body中初始化你的child变量:

class Parent {
  Parent() {
    child = Child(this);
  }

  Child child; // Cannot be final.
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多