【发布时间】:2014-09-14 00:44:08
【问题描述】:
我刚开始学习飞镖,但我看不懂 const 构造函数。谁能说明如何使用 const 构造函数。
什么情况下需要使用?
【问题讨论】:
标签: dart
我刚开始学习飞镖,但我看不懂 const 构造函数。谁能说明如何使用 const 构造函数。
什么情况下需要使用?
【问题讨论】:
标签: dart
您是否偶然发现了 Chris Strom 的 post about constant constructors? Chris Strom 在文章中所做的是对 final 字段的解释,但向下滚动到 cmets 部分,对来自某个 Lasse 的常量构造函数有一个很好的说明。
【讨论】:
注解中使用了常量对象:
import 'dart:mirrors';
class Foo{
final name;
const Foo(this.name);
}
@Foo("Bar")
class Baz{}
void main() {
ClassMirror cm = reflectClass(Baz);
print(cm.metadata.first.getField(#name).reflectee); // prints Bar
}
为什么要引入 const 对象(来自开发团队):
Why does Dart have compile time constants?
它们还可以提供额外的优化。比如我的dar2js实验:
Does dart2js optimize const objects better?
一些细节:
class Foo{
final baz;
const Foo(this.baz);
}
void main() {
//var foo = const Foo({"a" : 42}); //error {"a" : 42} is a mutable Map
var foo = const Foo(const {"a" : 42}); //ok
//foo.baz["a"] = 1; //error Cannot set value in unmodifiable Map
var bar = new Foo({"a" : 42}); //ok
//bar.baz = {"c" : 24}; //error NoSuchMethodError: method not found: 'baz='
bar.baz["a"] = 1; //ok;
}
如果类只有 const 构造函数,您仍然可以创建可变对象,newfinal baz 是不可变引用。但由于bar 是可变的,你可以更改baz 对象。
【讨论】: