gpt4 book ai didi

dart - Dart 中的 "const"和 "final"关键字有什么区别?

转载 作者:行者123 更新时间:2023-12-03 04:54:16 29 4
gpt4 key购买 nike

Dart 中的 constfinal 关键字有什么区别?

最佳答案

There is a post on dart's website and it explains it pretty well.

最终:

"final" means single-assignment: a final variable or field must have an initializer. Once assigned a value, a final variable's value cannot be changed. final modifies variables.

<小时/>

常量:

"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 objects have a couple of interesting properties and restrictions:

They must be created from data that can be calculated at compile time. A const object does not have access to anything you would need to calculate at runtime. 1 + 2 is a valid const expression, but new DateTime.now() is not.

They are deeply, transitively immutable. If you have a final field containing a collection, that collection can still be mutable. If you have a const collection, everything in it must also be const, recursively.

They are canonicalized. This is sort of like string interning: for any given const value, a single const object will be created and re-used no matter how many times the const expression(s) are evaluated.

<小时/>

那么,这意味着什么?

常量:
如果您拥有的值是在运行时计算的(例如,new DateTime.now()),您可以对其使用 const。但是,如果该值在编译时已知 (const a = 1;),则应使用 const 而不是 finalconstfinal 之间还有另外 2 个较大的差异。首先,如果您在类中使用 const,则必须将其声明为 static const 而不仅仅是 const。其次,如果您有一个 const 集合,则其中的所有内容都在 const 中。如果您有一个final集合,那么其中的所有内容都不是final

决赛:
如果您在编译时不知道该值,则应使用final而不是const,并且它将在运行时计算/获取。如果您想要一个无法更改的 HTTP 响应,如果您想从数据库中获取某些内容,或者如果您想从本地文件中读取数据,请使用 final。任何在编译时未知的内容都应该是 final 而不是 const

<小时/>

综上所述,constfinal 都不能重新分配,但 final 对象中的字段可以重新分配,只要它们本身不是 constfinal,可以重新分配(与 const 不同)。

关于dart - Dart 中的 "const"和 "final"关键字有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50431055/

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