【问题标题】:How can I call super inside constructor body?如何在构造函数体内调用 super?
【发布时间】:2020-02-03 05:32:00
【问题描述】:
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
  }
}

如何在构造函数体中调用super


注意:

我知道我可以使用初始化列表来解决它,但我想知道如何在方法体内调用super

Bar(int x): value = x, super(x); // works but I am not looking for it. 

【问题讨论】:

  • 据我所知,你不能。请问你想达到什么目的?
  • 我同意:你不能那样做。那么你想实现什么是通过在初始化列表中调用super 无法实现的呢?
  • @lrn 我来自 Java 背景,所以出于好奇,我想知道这是否会在 dart 中发生。
  • 那么答案是正确的:它不能。您只能在初始化列表中执行超级构造函数调用。调用超级构造函数后,主体完全运行。

标签: flutter dart


【解决方案1】:

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'
}

希望对你有帮助!

更新

你也可以使用这种方式调用超级构造函数,并在子构造函数中添加其他语句-

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);
}

【讨论】:

    猜你喜欢
    • 2012-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    • 2018-05-06
    • 2018-03-17
    相关资源
    最近更新 更多