gpt4 book ai didi

dart - Dart 中 "const"关键字的用途是什么?

转载 作者:行者123 更新时间:2023-12-03 00:27:49 25 4
gpt4 key购买 nike

有人可以向我解释如何/何时/为什么使用 const 关键字,或者它只是“声明常量变量的一种方法”?如果是这样,这有什么区别:

int x = 5;

const int x = 5;

能给我举个例子吗?

最佳答案

const 表示编译时常量。表达式值必须在编译时已知。 const 修改“值”。

来自news.dartlang.org ,

"const" has a meaning that's a bit more complex and subtle in Dart. const modifies values. You can use it when creating collections, like const [1, 2, 3], and when constructing objects (instead of new) like const Point(2, 3). Here, 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.

如果你使用

const x = 5 那么变量 x 可以在像

这样的 cosnt 集合中使用
const aConstCollection = const [x];

如果您不使用const,而仅使用x = 5,则

const aConstCollection = const [x]; 非法。

来自 www.dartlang.org 的更多示例

class SomeClass {
static final someConstant = 123;
static final aConstList = const [someConstant]; //NOT allowed
}

class SomeClass {
static const someConstant = 123; // OK
static final startTime = new DateTime.now(); // OK too
static const aConstList = const [someConstant]; // also OK
}

关于dart - Dart 中 "const"关键字的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13577512/

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