为什么Dart有编译时间常量? [英] Why does Dart have compile time constants?

查看:399
本文介绍了为什么Dart有编译时间常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Dart has the concept of compile-time constants. A compile-time constant is parsed and created at compile time, and canonicalized.

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

For example, here is a const constructor for 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构造函数。

This is a non-obvious feature, with seemingly no parallels to features in other dynamic languages. There are restrictions on const objects, like all fields must be final and it must have a const constructor.

Dart有编译时常量吗?

Why does Dart have compile-time constants?

推荐答案

Florian Loitsch从邮件列表中写道:

From the mailing list, Florian Loitsch writes:


编译时常量的规范化属性很好,但
不是主要原因。编译时
常量的真正好处是,它们不允许在
构造的任意执行,因此可以在我们不想要
代码执行的地方使用。例如,静态变量初始化器是
,最初限制为编译时常量,以避免在
顶级执行。总之,他们确保程序以
'main'开头,而不是其他地方。

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有编译时间常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆