Dart将其作为构造函数中的参数传递 [英] Dart pass this as a parameter in a constructor
问题描述
让我们说我有一个抽象类
Lets say that I have an abstract class
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屋!