【发布时间】: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的括号里会报错"什么错误?请显示完整的错误消息。