Dart 在构造函数中将此作为参数传递 [英] Dart pass this as a parameter in a constructor
问题描述
假设我有一个抽象类
abstract class OnClickHandler {
void doA();
void doB();
}
我有一堂课
class MyClass {
OnClickHandler onClickHandler;
MyClass({
this.onClickHandler
})
void someFunction() {
onClickHandler.doA();
}
}
我有一堂课
class Main implements onClickHandler {
// This throws me an error
MyClass _myClass = MyClass(onClickHandler = this); // <- Invalid reference to 'this' expression
@override
void doA() {}
@override
void doB() {}
}
我怎么能说使用与 Main 类相同的实现?或者有没有更简单/更好的方法来做到这一点?
How can I say that use the same implementations that the Main class has? or is there an easier/better way to do this?
推荐答案
您的问题是 this
尚不存在,因为对象仍在创建中.Dart 对象的构建分两个阶段完成,这可能难以理解.
Your problem is that this
does not yet exists since the object are still being created. The construction of Dart objects is done in two phases which can be difficult to understand.
如果您将程序更改为以下内容,它将起作用:
If you change you program to the following it will work:
abstract class OnClickHandler {
void doA();
void doB();
}
class MyClass {
OnClickHandler onClickHandler;
MyClass({this.onClickHandler});
void someFunction() {
onClickHandler.doA();
}
}
class Main implements OnClickHandler {
MyClass _myClass;
Main() {
_myClass = MyClass(onClickHandler: this);
}
@override
void doA() {}
@override
void doB() {}
}
原因是在构造函数中 { }
中运行的代码是在对象本身创建之后但在对象从构造函数返回之前执行的.
The reason is that code running inside { }
in the constructor are executed after the object itself has been created but before the object has been returned from the constructor.
这篇关于Dart 在构造函数中将此作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!