dart - Dart中的静态构造函数

标签 dart constructor static

如何在Dart中编写静态构造函数?

class Generator
{
   static List<Type> typesList = [];

   //static
   //{ /*static initializations*/}

}

最佳答案

Dart中没有静态构造函数。诸如Shape.circle()之类的命名构造函数是通过类似以下方式实现的

class A {
  A() {
    print('default constructor');
  }
  A.named() {
    print('named constructor');
  }
}

void main() {
  A();
  A.named();
}

您可能也对此factory constructors question感兴趣

更新:几个静态初始化程序解决方法
class A {
  static const List<Type> typesList = [];
  A() {
    if (typesList.isEmpty) {
      // initialization...
    }
  }
}

或者,如果静态内容不打算由该类的用户访问,则可以将其移出该类。
const List<Type> _typesList = [];
void _initTypes() {}

class A {
  A() {
    if (_typesList.isEmpty) _initTypes();
  }
}

关于dart - Dart中的静态构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59809875/

相关文章:

JavaScript继承: subtype prototype cannot visit super type's property/function

dart - 如何安装dart的第3方库

flutter - ListView 不可滚动时展开

c++ - 错误 : type ‘class’ is not a direct base of ‘class’

header 中的 C++ 数组

java - 将参数传递给 WordCram 代码

c++ - 静态局部变量可以减少内存分配时间吗?

c++ - 使用静态成员函数而不是普通函数会产生开销吗?

jquery-ui - 如何在Dart中使用javascript ui库

listview - Flutter - 滚动 ListView 时如何获得圆角边框?