void main() {
var list1 = const [1, 2, 3];
const list2 = [1, 2, 3];
}
Run Code Online (Sandbox Code Playgroud)
list1和list2有什么区别吗?
Dart 中“const”关键字放置有何不同?
Maj*_*jid 31
asconst关键字使您的对象constant以后无法为其重新分配任何值。
Const 意味着对象的整个深层状态可以在编译时完全确定,并且对象将被冻结且完全不可变。
在你的例子中
list1 = []; // perfectly fine
list2 = []; // but this throw errors (Error: Can't assign to the const variable 'list2'.)
Run Code Online (Sandbox Code Playgroud)
另一方面,var允许您为变量重新赋值。
然而,在const值使得值之后unmodifiable让我们看一个例子
list1.add(22); // ERROR! Cannot add to an unmodifiable list
// but you still can reassign the value
list1 = [];
// while the
list2 = []; // throw errors as I said above!
Run Code Online (Sandbox Code Playgroud)
const关键字变量中的值被const隐藏。
const list2 = const [1,2,3];
list2.add(22); // ERROR! Cannot add to an unmodifiable list
Run Code Online (Sandbox Code Playgroud)
简而言之:一个使分配的内存不可变,另一个使指向它的指针不变。在这两种情况下,列表(对象)都是不可变的。
我希望这可以帮助您理解其中的区别。
从dart.dev/language-tour#final-and-const上的官方文档中阅读更多内容
| 归档时间: |
|
| 查看次数: |
2268 次 |
| 最近记录: |