我正在尝试理解const关键字,我在const的GeeksforGeeks上找到了一篇文章,但我不理解它,如果我们让1,2常量,那么geek1,==,geek2将打印true,否则false如何?
// Declaring a function
gfg() =>[1, 2]; // if we write here gfg() => const [1, 2]; then geek1 == geek2 will print true
// Main function
void main() {
// Assiging value
// through function
var geek1 = gfg();
var geek2 = gfg();
// Printing result
// true
print(geek1 == geek2);
print(geek1);
print(geek2);
}发布于 2021-03-22 04:31:31
dart中数组的
==比较引用。这意味着,尽管两个数组具有相同的内容,但与==.const相比可以返回类定义编译时常量,但它也可以与false属性一起使用。重要的是,该函数返回相同的引用两次,而不是创建一个新数组。这两个函数之间的本质区别在于,在第一个函数中,每次调用函数时都定义一个新的数组(每次引用不同),而在第二个函数中定义一个编译时常量,每次调用函数时都会返回该常量(每次引用相同)。
让我们来看一些例子:
class Factory {
List<int> arr = [1, 2];
final finalArr = [1, 2];
static const constArr = [1, 2];
getValue() => [1, 2];
getInlineConst() => const [1, 2];
getRef() => arr;
getFinalRef() => finalArr;
getConstRef() => constArr;
}
void main() {
final f = new Factory();
print("values: ${f.getValue() == f.getValue()}");
print("const inline: ${f.getInlineConst() == f.getInlineConst()}");
print("reference: ${f.getRef() == f.getRef()}");
print("final reference: ${f.getFinalRef() == f.getFinalRef()}");
print("const reference: ${f.getConstRef() == f.getConstRef()}");
final refBefore = f.getRef();
f.arr = [1, 2];
final refAfter = f.getRef();
print("reference (with change inbetween): ${refBefore == refAfter}");
}输出为:
values: false
const inline: true
reference: true
final reference: true
const reference: true
reference (with change inbetween): false发布于 2021-03-22 16:54:29
Dart将常量规范化。这意味着程序的一个部分中的const Foo(1)的计算结果与程序的另一部分中的const Foo(1)相同。只有一个对象。这也扩展到常量列表:在程序中出现的任何地方,const [1, 2, 3]都会计算出相同的常量列表。
非常数对象创建会在每次求值时创建一个新对象:Foo(1)或new Foo(1)每次都会创建一个新对象。列表迭代也是如此。
因此,identical(const [1, 2, 3], const [1, 2, 3])是真的,但是identical([1, 2, 3], [1, 2, 3])是假的。
Dart内置列表的==不会比较列表的内容。它继承自Object,并且只检查它是否是相同的对象(基本上使用bool operator==(Object other) => identical(this, other);)。
https://stackoverflow.com/questions/66736120
复制相似问题