首页 > 解决方案 > 在超类中实例化子类?

问题描述

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

标签: dartoop

解决方案


你可以,但它要求你做很多你要求避免的工作:

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

目前,你不能继承构造函数,也不能创建你还不知道的类型的实例(因为构造函数不是继承的,所以你不知道构造函数是否存在)。抽象实际行为(要运行的代码)的唯一方法是在闭包中捕获它并将其作为函数传递。


推荐阅读