gpt4 book ai didi

dart - dart 中 `const [' foo', 'bar' ]` 中 const 的含义

转载 作者:行者123 更新时间:2023-12-03 02:49:34 26 4
gpt4 key购买 nike

我知道 const 是 dart 中的编译时常量,但我不明白以下代码中 const [F0, F1, F2] 背后的机制:

class Foo {
static const F0 = 'F0';
static const F1 = 'F1';
static const F2 = 'F2';
// const list of const values I guess...
static const CONST_LIST = const [F0, F1, F2]; // please explain this line
static final String FOO = CONST_LIST[0]; // ok
// compile error: 'const' varaibles must be constant value
// static const String BAR = CONST_LIST[1];
}

main() {
// is CONST_LIST const or not?
// below line it's ok for dartanalyzer but
// in runtime: Cannot change the content of an unmodifiable List
Foo.CONST_LIST[1] = 'new value';
}

我注意到 const 是 dart 分析器在 const [F0, F1, F2]; 中所必需的,但它确实使列表更像 final(运行时不可变列表)而不是比编译时常量。

更新:

另一个问题是为什么 CONST_LIST[1] 不是“常数值”。请参阅 Foo.BAR 的注释声明。

最佳答案

Günter 已经回答了您问题的第二部分。这里有一些关于 const 的更多信息。

Const means that the object's entire deep state can be determined entirely at compile time and that the object will be frozen and completely immutable.

article 中的更多信息.另见以下 question .

关于问题的第二部分,请考虑以下几点:

const int foo = 10 * 10;

表达式“10 * 10”可以在编译时求值,所以它是一个“常量表达式”。您可以在常量表达式中执行的操作类型必须非常有限(否则您可以在编译器中运行任意 Dart 代码!)。但是随着 dart 的成熟,其中一些限制正在放松,正如您在 Günter 链接到的错误中看到的那样。

相比之下,请考虑以下内容:

final int bar = 10;
final int foo = bar * bar;

因为“bar * bar”不是一个常量表达式,它在运行时被评估。

关于dart - dart 中 `const [' foo', 'bar' ]` 中 const 的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26957666/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com