“ var”与“ var”之间的区别和“动态”输入Dart吗? [英] Difference between "var" and "dynamic" type in Dart?

查看:88
本文介绍了“ var”与“ var”之间的区别和“动态”输入Dart吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这篇文章


您可能知道,动态(现在称为)是未提供静态类型注释时的替代类型。

As you might know, dynamic (as it is now called) is the stand-in type when a static type annotation is not provided.

因此,<$ c $和有什么区别? c> dynamic 和 var ?何时使用?

推荐答案

动态是所有Dart对象的基础类型。在大多数情况下,您无需显式使用它。

dynamic is a type underlying all Dart objects. You shouldn't need to explicitly use it in most cases.

var 是一个关键字,表示我不在乎指出什么类型在这里。 Dart将 var 关键字替换为初始值设定项类型,如果没有初始值设定项,则默认情况下将其保留为 dynamic

var is a keyword, meaning "I don't care to notate what the type is here." Dart will replace the var keyword with the initializer type, or leaving it dynamic by default if there is no initializer.

如果您希望变量赋值在生命周期内发生变化,请使用 var

Use var if you expect a variable assignment to change during its lifetime:

var msg = "Hello world.";
msg = "Hello world again.";

如果希望变量赋值在变量赋值期间保持不变,请使用 final 寿命:

Use final if you expect a variable assignment to remain the same during its lifetime:

final msg = "Hello world.";

(自由地)使用 final 可以帮助您发现意外更改的情况

Using final (liberally) will help you catch situations where you accidentally change the assignment of a variable when you didn't mean to.

请注意, final const 涉及对象。 最终不一定使对象本身不可变,而 const 确实:

Note that there is a fine distinction between final and const when it comes to objects. final does not necessarily make the object itself immutable, whereas const does:

// can add/remove from this list, but cannot assign a new list to fruit.
final fruit = ["apple", "pear", "orange"];
fruit.add("grape");

// cannot mutate the list or assign a new list to cars.
final cars = const ["Honda", "Toyota", "Ford"];

// const requires a constant assignment, whereas final will accept both:
const names = const ["John", "Jane", "Jack"];

这篇关于“ var”与“ var”之间的区别和“动态”输入Dart吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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