dart - 如何在 Dart 中使用复杂的参数调用 super()?
问题描述
根据我的研究,在 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);
}
}
这会引发分析错误(超类没有 0 参数构造函数并且表达式 super(3) 没有计算为函数,因此无法调用它)。我怎样才能实现示例的所需功能?
解决方案
在 Dart 中调用超级构造函数时使用了初始化列表。
class Shape extends Figure{
Shape(Form form) : super(form is Square ? 4 : form is Triangle ? 3 : null);
}
如果您需要执行语句,您可以添加一个工厂构造函数,该构造函数转发给一个(私有)常规构造函数,例如
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)
}
推荐阅读
- ios - Google Firebase 无法在 iOS 应用程序 XCode 中运行。Auth.auth.signIn() 方法不起作用
- continuous-integration - CD 环境中 CI 管道出现缓慢步骤并将其影响降至最低
- html - 角度自动完成选项不与输入保持位置
- python - 在无服务器部署时自动安装依赖项
- python-3.x - 如何在 python(pandas) 中使用 .loc 搜索确切的单词?
- python - 使用 RNN 进行预测后,如何将我的预测转换为文本?
- java - 我想在单击 imageView 时打开 Adapter 类,但我得到 ActivityNotFoundException,还有其他方法吗?
- swift - 如何使用 NSMutableAttributedString 设置 UILabel(不是 UITextView)圆角背景?
- node.js - npm package-lock 文件是如何生成依赖树的?
- google-compute-engine - GCP 是否对外部静态 IP 收费?