是否可以在 Dart 中使用默认私有构造函数扩展类?

cre*_*not 5 dart

假设我们有一个class a

class A {
  A._();
}
Run Code Online (Sandbox Code Playgroud)

它的默认构造函数private : A._()

有没有办法上extends那个课?

问题

class B extends A {

}
Run Code Online (Sandbox Code Playgroud)

这会导致编译器错误

The superclass 'A' doesn't have a zero argument constructor.
Run Code Online (Sandbox Code Playgroud)

尝试为自己 ( )编写任何构造函数会导致另一个错误:BB()

The superclass 'A' doesn't have an unnamed constructor.
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 5

不,没有办法。这是防止扩展的有效方法。

你仍然可以做的是实现这个类。

class B implements A {}
Run Code Online (Sandbox Code Playgroud)

如果类还有一个公共的非工厂构造函数,你仍然可以通过将构造函数调用转发到超类的这样一个命名构造函数来扩展它。

class B extends A {
  B() : super.other();
}
Run Code Online (Sandbox Code Playgroud)