dart中的var和其他更具体的类型之间的区别 [英] Difference between var and other more specific types in dart
问题描述
我来自Javascript的"let",我对var和其他类型之间的最大区别感到困惑.我了解在某些情况下需要使用var(匿名数据类型),在某些情况下需要使用显式类型.我也了解var不够简洁,类型更多,但是在Flutter开发中是否有使用深度代替var的更深入或实际的应用?
I come from Javascript's "let", and I am a bit confused on what the big differences are between var and other types. I understand that there are some cases where we need to use var(anonymous data types), and some where we need to use explicit types. I also understand that the var is less concise and the types are more, but is there a more in depth or practical application of using types instead of var within Flutter development?
推荐答案
您永远不需要使用 var
;您总是可以选择指定一个显式类型.
You never need to use var
; you always can choose to specify an explicit type instead.
var
.(如果没有初始化程序,则该变量的类型将为 dynamic
.但是,由于 dynamic
禁用了该变量的静态类型检查,并且会产生额外的运行时成本,因此您 dynamic
(如果可能),并且在必要时应将变量显式指定为 dynamic
.
var
is used if you want to declare a variable and want the type to be inferred from the initializer. (If there is no initializer, the variable will be of type dynamic
. However, since dynamic
disables static type checking for that variable and incurs an extra runtime cost, you should avoid dynamic
when possible and should explicitly variables as dynamic
when it's necessary.
如果变量类型是可推断的,则使用隐式类型还是显式类型都取决于样式.
If the variable type is inferrable, whether you use implicit or explicit types is a matter of style.
使用显式类型的优点:
- 无需工具(例如,没有可以显示变量类型的IDE支持),可读性会更高.
- 可以在推断出的类型不是预期的类型时捕获类型错误.
使用隐式类型的优点:
- Less verbose, which arguably makes the rest of the code more readable.
- Can avoid type errors where the explicit type is accidentally less precise than the inferred type. For example:
List someList = [1, 2, 3];
actually declaressomeList
to be of typeList<dynamic>
even though the right-hand-side is inferred to beList<int>
.
这篇关于dart中的var和其他更具体的类型之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!