为什么要"var"?而不是数据类型被认为是Dart中的更好做法? [英] Why "var" instead of data type is considered a better practice in Dart?

查看:54
本文介绍了为什么要"var"?而不是数据类型被认为是Dart中的更好做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Dart,在本教程中提到,当您初始化变量时,请使用关键字"var".而不是像"int"这样的数据类型.Dart将自动推断出它是一个"int"标记.或字符串"根据初始值.但是,如果我们直接告诉飞镖将要进入整数",那会不会更快.Dart是强类型的,因此我们不能对整数和字符串使用相同的变量,例如"javascript",那么"var"的目的是什么?在飞镖环境中.在我看来,使用数据类型将更快,更轻松.为什么使用"var"被认为是更好的做法?

I was studying Dart and it is mentioned in the tutorial that when you are initializing the variable, use the keyword "var" instead of the type of data like "int". Dart will automatically infer that it is an "int" or "String" based on the initial value. But will it not be faster if we tell the dart directly that it is going to an "int". Dart is strongly typed and we cannot use the same variable for an integer and string like "javascript", then what is the purpose of "var" in dart context. It seems to me that using data type will be faster and easier. Why it is considered a better practice to use the "var"?

推荐答案

类型为 dynamic 的变量类似于javascript,它可以在运行时更改类型.例如,存储一个整数然后更改为字符串.

A variable of type dynamic would be similar to javascript where it can change type during runtime. For example store an integer then change to a string.

var 与dynamic不同. var 是初始化变量的简便方法,因为您不必显式声明类型.Dart只是推断类型以使其更容易使用.如果您编写 int number = 5 ,它将与 var number = 5 相同,因为dart会推断此变量是整数.

var is not the same as dynamic. var is an easy way to initialise variables as you don't have to explicitly state the type. Dart just infers the type to make it easier for you. If you write int number = 5 it would be the same as var number = 5 as dart would infer that this variable is an integer.

本教程可能会说 var int 更好的原因可能是使代码更具可读性的惯例,但我认为它不会对代码产生任何影响您的代码.您可以使用任何一种,都不会有所不同.

The reason the tutorial might have said that var is better than int may be convention to make the code more readable but I believe it doesn't have any impact on your code. You can use either and it won't make a difference.

这篇关于为什么要"var"?而不是数据类型被认为是Dart中的更好做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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