在参数化列表上的飞镖混乱 [英] dart confusion on parameterized List

查看:120
本文介绍了在参数化列表上的飞镖混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此代码不会引发错误?

Why this code no raise an error?

List<String> x;

void main() {
  x = [1,23,3,423,2];
  print(x);
}

对不起的新手问题,但我只是开始学习dart,这是因为我理解 x 只能包含 String 的列表,并且应该引发异常不是 String 的列表,而是 num 的列表。这是一个错误,或?

Sorry for the newbie question, but i just start learning dart, and i ask this because of my understanding that the x can only contain a list ofString and should raise an exception due to the value not a list of String but a list of num. This is a bug, or?

推荐答案

这是一个可选的输入操作。

This is optional typing in action.

var x; // same as List<String> x
List<String> y;

main() {
  x = [1,2,3,4];
  y = x; // valid
  x = y; // valid
  print(x); // [1,2,3,4]
  print(y); // [1,2,3,4]
}

c $ c> List< String> 或 var ,代码将执行相同的操作。工具使用类型注释( List< String> )验证您的代码。

Whether you specify List<String> or var, your code will execute the same. The type annotations (List<String>) are used by the tools to verify your code.

在dartlang网站上阅读的内容是关于可选类型的信息。

A good article to read on the dartlang site is one about optional types.

编辑:实际上,这也是关于列表的一个有趣的点。如果你使用文字列表初始化一个列表(例如 [] ),那么你实际上创建了一个 List(),例如:

Actually, this is also an interesting point about Lists. If you initialize a list using a literal list( eg, []), then you are actually creating a List(), eg:

main() {
  var x = new List(); 
  var y = [];
  print(x is List); // true
  print(y is List); // true
}

然而,如果你想要一个使用泛型的类型列表,必须使用构造函数语法,例如:

If, however, you want a typed list using generics, you must use the constructor syntax, eg:

main() {
  var x = new List<String>();
  print(x is List); // true
  print(x is List<String>); // true
  print(x is List<num>); // false
}

这篇关于在参数化列表上的飞镖混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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