在Dart中,静态成员,最终成员和const成员在编译时有什么区别?

时间:2018-12-27 14:56:25

标签: dart flutter access-modifiers

就像标题所示,在Dart中,编译时的static,final和const有什么区别?

何时计算它们?何时为每种类型分配内存? 大量使用静态变量会导致性能问题或OOM吗?

2 个答案:

答案 0 :(得分:3)

static用于声明类级别的成员(方法,字段,getter / setter)。 它们在类的名称空间中。只能从类(而不是子类)内部或以类名作为前缀来访问它们。

class Foo {
  static bar() => print('bar');

  void baz() => bar(); // ok
}

class Qux extens Foo {
  void quux() => bar(); // error. There is no `bar()` on the `Qux` instance
}

main() {
  var foo = Foo();
  foo.bar(); // error. There is no `bar` on the `Foo` instance.
  Foo.bar(); // ok
}

const用于编译时间常数。 Dart允许使用一组有限的表达式来计算编译时间常数。 const个实例已规范化。这意味着将规范化多个const Text('foo')(具有相同的'foo'参数值),无论此代码在您的应用程序中的位置和频率如何,都只会创建一个实例。

class Foo {
  const Foo(this.value);

  // if there is a const constructor then all fields need to be `final`
  final String value;
}
void main() {
  const bar1 = Foo('bar');
  const bar2 = Foo('bar');
  identical(bar1, bar2); // true 
}

final仅表示只能在声明时分配给它。

对于实例字段,这意味着在字段初始值设定项中,通过用this.foo分配的构造函数参数或在构造函数初始值设定项列表中,但在执行构造函数主体时不再有效。

void main() {
  final foo = Foo('foo');
  foo = Foo('bar'); // error: Final variables can only be initialized when they are introduced
}

class Foo {
  final String bar = 'bar';
  final String baz;
  final String qux;

  Foo(this.baz);
  Foo.other(this.baz) : qux = 'qux' * 3;
  Foo.invalid(String baz) {
  // error: Final `baz` and `qux` are not initialized
    this.baz = baz;         
    this.qux = 'qux' * 3;
  }
}

答案 1 :(得分:1)

静态变量不需要使用该类的实例。

示例:

class Math {
  static var double staticPi = 3.14;
  double var pi = 3.14;
}

class ClassThatUsesMath {
  print(Math.staticPi);

  // Non-static variable must initialize class first:
  Math math = Math();
  print(math.pi);
}

最终变量的值在分配值后无法更改。

示例:

class Math {
  final var pi = 3.14;
  pi = 3.1415;  // Error!
}

const 变量与final相似,因为它是不可变的(无法更改)。但是,const值必须能够在编译时计算。 const值也将被重用,而不是被重新计算。

示例:

class MathClass {
  const var section = 4;
  const var examTime = DateTime.now();  // Error! Cannot be determined at compile time.
}