[英]What is the difference between "List names" and "List<String> names" in Dart?
What is the difference between the following two statements:以下两种说法有什么区别:
List names = ["John", "Robert", "James"];
List<String> names = ["John", "Robert", "James"];
Dart will in the first example assume the type should be List<dynamic>
since you have just told the type system that you want a List
without any specific restrictions.在第一个示例中,Dart 将假定类型应该是
List<dynamic>
因为您刚刚告诉类型系统您想要一个没有任何特定限制的List
。
In the second example, the created list are getting the type List<String>
since you have provided a restriction of the type of elements you want in the list.在第二个示例中,创建的列表的类型为
List<String>
,因为您提供了对列表中所需元素类型的限制。
Another example would be the following:另一个例子如下:
var names = ["John", "Robert", "James"]; // or final instead of var
Here we are letting Dart automatically determine the most restrictive type possible.在这里,我们让 Dart 自动确定可能的最严格的类型。 In this case, the
names
are going to be automatically typed List<String>
.在这种情况下,
names
将自动键入List<String>
。
You can see this if you print the runtimeType
of each declared list:如果您打印每个声明的列表的
runtimeType
,您可以看到这一点:
void main() {
List names1 = ["John", "Robert", "James"];
print(names1.runtimeType); // List<dynamic>
List<String> names2 = ["John", "Robert", "James"];
print(names2.runtimeType); // List<String>
var names3 = ["John", "Robert", "James"];
print(names3.runtimeType); // List<String>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.