简体   繁体   English

Dart 中的静态构造函数

[英]static constructor in Dart

How to write static constructor in Dart?如何在 Dart 中编写静态构造函数?

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

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

}

There is no such thing as a static constructor in Dart. Dart 中没有静态构造函数这样的东西。 Named constructors such as Shape.circle() are achieved by something like命名构造函数如Shape.circle()是通过类似的东西实现的

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

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

You might also be interested in this factory constructors question您可能还对这个工厂构造函数问题感兴趣

Update: A couple of static initializer work-arounds更新:一些静态初始值设定项的变通方法

class A {
  static const List<Type> typesList = [];
  A() {
    if (typesList.isEmpty) {
      // initialization...
    }
  }
}

Or the static stuff can be moved out of the class if it isn't meant to be accessed by users of the class.或者,如果类的用户不打算访问静态内容,则可以将其移出类。

const List<Type> _typesList = [];
void _initTypes() {}

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

You can initialize static members by calling the class.member directly, inside the constructor:您可以通过在构造函数中直接调用 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);
}

Inspired by @Mahmoud salah eldien saber answer Create a singleton, and static variable reference to the singleton variable灵感来自@Mahmoud salah eldien saber 答案创建单例,以及对单例变量的静态变量引用

void main() {
  
  print('${Singleton.add()}');
  print('${Singleton.add()}');
  print('${Singleton.add()}');
  print('${Singleton.add()}');     
}

class Singleton {
  Singleton();
    
  //static
  static List<int> typeList = Singleton.internal()._typeList;
  static List<int> add() {
    typeList.add(1);
    return typeList;
  }  
  List<int> _typeList = [];
  factory Singleton.internal() {  
    var s = Singleton();
    for(int i = 0 ; i < 5; i++ ) {
      s._typeList.add(2);
    }   
    return s;
  }    
   
}

I also want to find a official answer for this question.我也想找到这个问题的官方答案。

Static variable declarations are initialized lazily to avoid costly initialization (and attendant slowness) at program startup.. The first time a static variable v is read, it is set to the result of evaluating its initializer.静态变量声明被延迟初始化以避免在程序启动时代价高昂的初始化(以及随之而来的缓慢)。第一次读取静态变量 v 时,它被设置为评估其初始化程序的结果。

https://groups.google.com/a/dartlang.org/forum/#!topic/misc/dKurFjODRXQ https://groups.google.com/a/dartlang.org/forum/#!topic/misc/dKurFjODRXQ

To create static (constuctor or class) it's very easy in dart, just create static vaiable in this class and give it object from the same class:要创建静态(构造函数或类),在 dart 中非常容易,只需在此类中创建静态变量并为其提供来自同一类的对象:

class A {
  static var instance = A();
  static List<int> typesList = [];
  A() {
    print('Call constructor to create object');
  }
  List<int> add() {
    typesList.add(1);
    return typesList;
  }
}

void main() {
  print(A.instance.add());
  print(A.instance.add());
  print(A.instance.add());
  print(A.instance.add());
}

One of the workarounds to initialize static variables could be to use ".." (called "cascade") operator.初始化静态变量的一种解决方法可能是使用“..”(称为“级联”)运算符。 This workaround doesn't require object instance.此解决方法不需要对象实例。 More about cascade operator: https://dart.dev/guides/language/language-tour#cascade-notation- .有关级联运算符的更多信息: https : //dart.dev/guides/language/language-tour#cascade-notation-

Example:例子:

static List firstList = [ 'hello', 12, 'goodbye'];

static List dummyObjects = List()
    ..addAll(firstList)
    ..add('another String value')
    ..add('and one more')
    ..add(Object())
    ..removeWhere((o) => o is! String)
;

(So dummyObjects is initialized only with objects that are of type String because all others discarded.) (因此dummyObjects仅使用 String 类型的对象初始化,因为所有其他对象都被丢弃了。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM