在超类中实例化子类?

Instantiating a subclass in a superclass?

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

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