我如何在构造函数中使用`this`?

问题描述 投票:0回答:1

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

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

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

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

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代码中演示的行为?

python flutter dart this self
1个回答
0
投票

您不能在构造函数头或初始化列表中都访问this(了解有关here的更多信息。

如果要执行此操作,则必须在构造函数body中初始化child变量:

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

  Child child; // Cannot be final.
}
© www.soinside.com 2019 - 2024. All rights reserved.