在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代码中演示的行为?
您不能在构造函数头或初始化列表中都访问this
(了解有关here的更多信息。
如果要执行此操作,则必须在构造函数body中初始化child
变量:
class Parent {
Parent() {
child = Child(this);
}
Child child; // Cannot be final.
}