gpt4 book ai didi

dart - 为什么 Dart 有编译时常量?

转载 作者:行者123 更新时间:2023-12-04 00:52:59 24 4
gpt4 key购买 nike

Dart 有编译时常量的概念。编译时常量在编译时被解析和创建,并被规范化。

例如,这里是 const Point 的构造函数:

class Point {
final num x, y;
const Point(this.x, this.y);
}

以下是您如何使用它:
main() {
var p1 = const Point(0, 0);
var p2 = const Point(0, 0);
print(p1 == p2); // true
print(p1 === p2); // true
}

这是一个不明显的特性,与其他动态语言中的特性似乎没有相似之处。 const有限制对象,就像所有字段都必须是 final 并且它必须有一个 const 构造函数。

为什么 Dart 有编译时常量?

最佳答案

来自 mailing list , 弗洛里安·洛伊奇 (Florian Loitsch) 写道:

The canonicalization property of compile-time constants is nice, but not the main-reason to have them. The real benefit of compile-time constants is, that they don't allow arbitrary execution at construction and can therefore be used at places where we don't want code to executed. Static variables initializers, for example, were initially restricted to compile-time constants to avoid execution at the top-level. In short, they make sure that a program starts with 'main' and not somewhere else.

关于dart - 为什么 Dart 有编译时常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12418819/

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