簡體   English   中英

Dart泛型類實例化

[英]Dart generic class instantiation

在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>>();

但這不是我想要面對這個問題的重點。 謝謝。

不,它們不是等價的,實例化在運行時類型上有所不同,您可能會在使用運行時類型的代碼中遇到意外 - 比如類型檢查。

new Map()new Map<dynamic, dynamic>()的快捷方式,意思是“映射你想要的任何東西”。

測試略有修改的原始實例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM