Difference between “var” and “dynamic” type in Dart?
根据本文:
As you might know,
dynamic (as it is now called) is the stand-in type when a static type annotation is not provided.
那么,
dynamic是所有Dart对象基础的类型。在大多数情况下,您不需要显式使用它。
var是关键字,意思是"我不在乎指出这里的类型"。 Dart会将var关键字替换为初始值设定项类型,如果没有初始值设定项,则默认情况下将其保持动态状态。
如果希望变量赋值在其生命周期内发生变化,请使用var:
1 2 | var msg ="Hello world."; msg ="Hello world again."; |
如果希望变量赋值在其生命周期内保持不变,请使用final:
1 | final msg ="Hello world."; |
(最终使用)final(帮助)可以帮助您发现在无意的情况下意外更改了变量赋值的情况。
请注意,对于对象,final和const之间有很好的区别。 final不一定使对象本身不可变,而const可以:
1 2 3 4 5 6 7 8 9 | // 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"]; |
在DartPad中尝试:
1 2 3 4 5 6 7 8 | void main() { dynamic x = 'hal'; x = 123; print(x); var a = 'hal'; a = 123; print(a); } |
您可以更改x的类型,但不能更改a。
dynamic:可以更改变量的TYPE,
与
在大多数情况下,Dart足够聪明,可以知道确切的类型。例如,以下两个语句是等效的:
1 2 3 | String a ="abc"; // type of variable is String var a ="abc"; // a simple and equivalent (and also recommended) way // to declare a variable for string types |
另一方面,
1 2 | (foo as dynamic).whatever(); //valid. compiler won't check if whatever() exists (foo as var).whatever(); //illegal. var is not a type |
1 2 3 4 5 6 | var a ; a = 123; print(a is int); print(a); a = 'hal'; print(a is String); |
在没有初始值的情况下定义var是动态的
1 2 3 4 5 | var b = 321; print(b is int); print(b); //b = 'hal'; //error print(b is String); |
使用初始值定义时,在这种情况下,var是int。
为阐明先前的一些答案,当您将变量声明为
例如,以下代码:
1 2 3 4 | dynamic foo = 'foo'; print('foo is ${foo.runtimeType} ($foo)'); foo = 123; print('foo is ${foo.runtimeType} ($foo)'); |
在DartPad中运行时,
将返回以下结果:
1 2 | foo is String (foo) foo is int (123) |
但是以下代码甚至无法编译:
1 2 3 4 | var bar = 'bar'; print('bar is ${bar.runtimeType} ($bar)'); bar = 123; // <-- Won't compile, because bar is a String print('bar is ${bar.runtimeType} ($bar)'); |
长话短说-如果要使用非类型化变量,请使用
动态vs var比较中可以考虑的一个方面是在同时使用带有初始化的var声明时考虑到行为,因此不可能更改在动态情况下的类型。
但是,动态vs var并不是我要问的问题。
我想问更多动态对象之间的区别。
这是一个用Object而不是动态的DO注释,表示允许任何对象。
在开始时很难感觉到它,但是动态的我将涉及泛型类型参数。
n
n
n
n