【问题标题】:Dart generic class instantiationDart 泛型类实例化
【发布时间】:2016-08-27 19:48:37
【问题描述】:

在 Dart 中这两个实例化是等价的吗?

//version 1
Map<String, List<Component>> map = new Map<String, List<Component>>();

//version 2
Map<String, List<Component>> map = new Map(); //type checker doesn't complain

使用版本 2 是否有任何问题(我更喜欢它,因为它不那么冗长)?

请注意,我知道我可以使用:

var map = new Map<String, List<Component>>();

但这不是我想面对这个问题的重点。谢谢。

【问题讨论】:

  • 如果你不启用强模式,Dart 分析器对类型并不是特别挑剔。在生产模式下运行时,类型注释将被完全忽略。
  • 我启用了“强模式”,但无论如何我都没有在“new Map()”上收到任何错误或警告。那没有回答我的问题。如果有人想知道如何启用“强模式”,这里有一个有用的链接:pub.dartlang.org/packages/analyzer

标签: generics dart instantiation type-inference


【解决方案1】:

不,它们不是等效的,实例化在运行时类型上有所不同,并且在使用运行时类型的代码中您可能会遇到意外——比如类型检查。

new Map()new Map&lt;dynamic, dynamic&gt;() 的快捷方式,意思是“映射任何你想要的东西”。

测试稍微修改的原始实例:

main(List<String> args) {
  //version 1
  Map<String, List<int>> map1 = new Map<String, List<int>>();
  //version 2
  Map<String, List<int>> map2 = new Map(); // == new Map<dynamic, dynamic>();

  // runtime type differs
  print("map1 runtime type: ${map1.runtimeType}");
  print("map2 runtime type: ${map2.runtimeType}");

  // type checking differs
  print(map1 is Map<int, int>); // false
  print(map2 is Map<int, int>); // true

  // result of operations the same
  map1.putIfAbsent("onetwo", () => [1, 2]);
  map2.putIfAbsent("onetwo", () => [1, 2]);
  // analyzer in strong mode complains here on both
  map1.putIfAbsent("threefour", () => ["three", "four"]);
  map2.putIfAbsent("threefour", () => ["three", "four"]);

  // content the same
  print(map1);
  print(map2);
}

update1:​​DartPad 中的代码可以使用。

update2: 未来强模式似乎会抱怨map2实例化,见https://github.com/dart-lang/sdk/issues/24712

【讨论】:

    猜你喜欢
    • 2015-03-06
    • 2013-10-03
    • 2011-04-02
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    • 2014-05-31
    相关资源
    最近更新 更多