如何在 Dart 中使用复杂参数进行 super() 调用?

Nic*_*ich 8 dart

根据我的研究,在 Dart 中,您必须在构造函数的函数体之外调用 super。

假设这种情况:

/// Unmodifiable given class
class Figure{
  final int sides;
  const Figure(this.sides);
}

/// Own class
class Shape extends Figure{
  Shape(Form form){
    if(form is Square) super(4);
    else if(form is Triangle) super(3);
  }
}
Run Code Online (Sandbox Code Playgroud)

这会引发分析错误(超类没有 0 参数构造函数并且表达式 super(3) 不计算为函数,因此无法调用它)。我怎样才能实现该示例所需的功能?

Gün*_*uer 17

在 Dart 中调用超级构造函数使用了初始化列表

class Shape extends Figure{
  Shape(Form form) : super(form is Square ? 4 : form is Triangle ? 3 : null);
}
Run Code Online (Sandbox Code Playgroud)

如果您需要执行语句,您可以添加一个工厂构造函数,该构造函数转发到(私有)常规构造函数,例如

class Shape extends Figure{

  factory Shape(Form form) {
    if (form is Square) return new Shape._(4);
    else if(form is Triangle) return new Shape._(3);
  }
  Shape._(int sides) : super(sides)
}
Run Code Online (Sandbox Code Playgroud)