Ari*_*rif 7 static constructor dart
如何在 Dart 中编写静态构造函数?
class Generator
{
static List<Type> typesList = [];
//static
//{ /*static initializations*/}
}
Run Code Online (Sandbox Code Playgroud)
Dart 中没有静态构造函数这样的东西。命名构造函数,例如Shape.circle()是通过类似的东西实现的
class A {
A() {
print('default constructor');
}
A.named() {
print('named constructor');
}
}
void main() {
A();
A.named();
}
Run Code Online (Sandbox Code Playgroud)
您可能还对这个工厂构造函数问题感兴趣
更新:一些静态初始值设定项的变通方法
class A {
static const List<Type> typesList = [];
A() {
if (typesList.isEmpty) {
// initialization...
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者,如果类的用户不打算访问静态内容,则可以将其移出类。
const List<Type> _typesList = [];
void _initTypes() {}
class A {
A() {
if (_typesList.isEmpty) _initTypes();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过在构造函数中直接调用 class.member 来初始化静态成员:
class A {
static int a;
static int b;
A(int a, int b) {
A.a ??= a; ///by using the null-equals operator, you ensure this can only be set once
A.b ??= b;
}
}
main(){
A(5,10);
A(2,4);
assert(A.a == 5);
assert(A.b == 10);
}
Run Code Online (Sandbox Code Playgroud)