我有这样的课程:
class A extends B {
final Property<bool> property = Property<bool>(this);
}
class Property<T> {
Property(this.b);
final B b;
}
但是我在this
上说了一个错误:
对“ this”表达式的引用无效。
我相信我当时无法访问this
,可能是因为对象引用尚未准备好。
所以我尝试了其他形式的变量初始化:
class A extends B {
final Property<bool> property;
A() : property = Property<bool>(this);
}
但是我遇到同样的错误。
唯一起作用的是:
class A extends B {
Property<bool> property;
A() {
property = Property<bool>(this);
}
}
这需要我删除final
变量声明,这是我不想要的。
如何在Dart中初始化需要引用对象本身的final
变量?
您无法在任何初始化程序中引用this
,因为this
本身尚未进行初始化,因此您将无法将Property<bool> property
设置为最终值。