dart - 在超类中实例化子类?
问题描述
abstract class A {
A(this.x, this.y);
// error: abstract classes cannot be instantiated
//
// another issue: even if you used a base concrete class
// to perform this operation, it would lose type information.
A copy({int? x, int? y}) => A(x ?? this.x, y ?? this.y);
final int x;
final int y;
}
class B extends A {
// Forced to implement copy and similar
// methods on all classes that extend A,
// which is problematic when that number
// is large or changes are necessary.
}
有没有办法解决这个问题,还是我必须为所有扩展的类重写相同的代码A
?
解决方案
你可以,但它要求你做很多你要求避免的工作:
class A<T extends A<T>> {
final T Function(int, int) _constructor;
final int x;
final int y;
A._(this._constructor, this.x, this.y);
T copy({int? x, int? y}) => _constructor(x ?? this.x, y ?? this.y);
}
class B extends A<B> {
B(int x, int y) : super._((int x, int y) => B(x, y), x, y);
}
(当 Dart 获得构造函数撕裂时,代码会变得更短,那么它只是,super._(B, x, y);
。)
目前,你不能继承构造函数,也不能创建你还不知道的类型的实例(因为构造函数不是继承的,所以你不知道构造函数是否存在)。抽象实际行为(要运行的代码)的唯一方法是在闭包中捕获它并将其作为函数传递。
推荐阅读
- ssl - TLS 握手失败并出现错误 tls:第一条记录看起来不像 TLS 握手服务器=Orderer remoteaddress=192.168.144.4:43496
- jquery - 用于数据表的 Ajax 源数据
- c# - 通过 32feet.Net 库连接蓝牙设备
- php - 如何在 Laradock 中安装 Mosquitto-php
- apache-spark - 在 Spark 中读取具有多个标题的文本文件
- comma - 如何在此输出中添加空格或逗号?
- python - python pandas中child_id和parent_id值的加法
- amazon-web-services - 如何进行 AWS S3 SSE KMS 密钥轮换?
- java - 外化spring属性文件后找不到Bean SpringTemplateEngine错误
- kendo-ui - 使用 Base-unit 在同一月份绘制两条不同日期的线:月