class Foo {
Foo(int y);
}
class Bar extends Foo {
int value;
Bar(int x) { // error in this line
value = x;
print("Hi there");
super(x); // error in this line
}
}
Run Code Online (Sandbox Code Playgroud)
如何super在构造函数体内调用?
笔记:
我知道我可以使用初始化列表来解决它,但我想知道如何在super方法体内调用?
Bar(int x): value = x, super(x); // works but I am not looking for it.
Run Code Online (Sandbox Code Playgroud)
Dart 不支持将构造函数继承为显式可调用方法。您提到的初始值设定项列表是在 Dart 中调用未命名超级构造函数的受支持方式。
但是,您可以借助命名构造函数来实现您想要的目的。看看下面的例子 -
class Foo {
int superValue;
Foo(); //A default zero-argument constructor
Foo._init(this.superValue); //Named constructor
void initValue(int x) => Foo._init(x);
}
class Bar extends Foo {
int value;
Bar(int x) {
value = x;
print("Hi there");
super.initValue(x);
}
}
void main() {
Foo foo = Bar(10); //prints 'Hi there'
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你!
更新
您还可以使用这种方式调用超级构造函数并向子构造函数添加其他语句 -
class Foo {
int superValue;
Foo(this.superValue);
}
class Bar extends Foo {
int value;
Bar(int x) : super(x) {
value = x;
print("Hi there");
}
}
void main() {
Foo foo = Bar(10);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1308 次 |
| 最近记录: |