void main() {
var list1 = const [1, 2, 3];
const list2 = [1, 2, 3];
}
列表1和列表2之间有什么区别吗?
Dart中"const"关键字的位置有什么不同?
- 在列表文字前的"const"和变量名前的"const"之间
void main() {
var list1 = const [1, 2, 3];
const list2 = [1, 2, 3];
}
列表1和列表2之间有什么区别吗?
Dart中"const"关键字的位置有什么不同?
const
as关键字会使您的对象变成constant
,您以后无法为其重新分配任何值.
Const意味着对象的整个深层状态可以在编译时完全确定,并且对象将被冻结且完全不可变.
在你的例子中
list1 = []; // perfectly fine
list2 = []; // but this throw errors (Error: Can't assign to the const variable 'list2'.)
另一方面,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!
const
关键字变量中值的const
被隐藏.
const list2 = const [1,2,3];
list2.add(22); // ERROR! Cannot add to an unmodifiable list
简而言之:一个使分配的内存不可变,另一个相同,还有指向它的指针.在这两种情况下,列表(对象)都是不可变的.
我希望这能帮助你理解其中的区别.