现有映射中的 .from() 和 .of() 有什么区别?



在Dart中,这两者都是可能的。

Map<String, int> map1 = {'zero': 0, 'one': 1, 'two': 2};
Map map2 = Map.from(map1);
print(map2);
Map map3 = Map.of(map1);
print(map3);

他们输出这个。

{zero: 0, one: 1, two: 2}
{zero: 0, one: 1, two: 2}

那么,两者之间有什么区别呢?

也许这与他们的复制方式有关,有什么帮助吗?

Map.from()Map.of()分别重定向到LinkedHashMap<K, V>.fromLinkedHashMap<K, V>.of。以下是LinkedHashMap的.from().of()的源代码。

/// Creates a [LinkedHashMap] that contains all key value pairs of [other].
///
/// The keys must all be instances of [K] and the values to [V].
/// The [other] map itself can have any type.
factory LinkedHashMap.from(Map other) {
LinkedHashMap<K, V> result = LinkedHashMap<K, V>();
other.forEach((k, v) {
result[k] = v;
});
return result;
}
/// Creates a [LinkedHashMap] that contains all key value pairs of [other].
factory LinkedHashMap.of(Map<K, V> other) =>
LinkedHashMap<K, V>()..addAll(other);

正如注释中所写的,正如您从代码中看到的,.from()接受具有任何键/值类型的映射,而.of()只能接受Map<K, V>

void main() async {
Map<String, int> map1 = {'zero': 0, 'one': 1, 'two': 2};
final map2 = Map<String, double>.from(map1);
print(map2); // {'zero': 0, 'one': 1, 'two': 2}
/*
// This fails because the passed map is not Map<String, double> but Map<String, int>.
final map2 = Map<String, double>.of(map1);
*/
final map3 = Map<String, int>.of(map1);
print(map3); // {'zero': 0, 'one': 1, 'two': 2}
}

最新更新