无法将keyValuePair直接添加到Dictionary

我想将KeyValuePairDictionary ,但我不能。 我必须分别传递密钥和值,这必然意味着Add方法必须创建一个新的KeyValuePair对象来插入,这不是非常有效。 我不敢相信Add方法上没有Add(KeyValuePair)重载。 任何人都可以提出这种明显疏忽的可能原因吗?

备份一分钟…在走向疏忽的道路之前,你应该确定创建一个新的KeyValuePair是否真的如此低效。

首先,Dictionary类在内部不是作为一组键/值对实现的,而是作为一堆数组实现的。 除此之外,让我们假设它只是一组KeyValuePairs并着眼于效率。

首先要注意的是KeyValuePair是一个结构。 真正的含义是必须将它从堆栈复制到堆中才能作为方法参数传递。 将KeyValuePair添加到字典时,必须再次复制它以确保值类型语义。

为了将Key和Value作为参数传递,每个参数可以是值类型或引用类型。 如果它们是值类型,则性能将与KeyValuePair路由非常相似。 如果它们是引用类型,这实际上可以是更快的实现,因为只需要传递地址并且必须进行非常少的复制。 在最佳情况和最坏情况下,由于KeyValuePair结构本身的开销增加,此选项略微优于KeyValuePair选项。

您可以使用IDictionary界面,该界面提供Add(KeyValuePair)方法:

 IDictionary dictionary = new Dictionary(); dictionary.Add(new KeyValuePair(0,"0")); dictionary.Add(new KeyValuePair(1,"1")); 

有这样一种方法 – ICollection>.Add但是因为它是显式实现的,你需要将你的字典对象转换为该接口来访问它。

 ((ICollection>)myDict).Add(myPair); 

看到

  • Dictionary的文档页面上的显式接口实现列表(您需要向下滚动)。
  • 明确的成员实施

此方法的页面包含一个示例。

除非我弄错了,否则.NET 4.5和4.6增加了将KeyValuePair添加到Dictionary的function。 (如果我错了,请通知我,我会删除这个答案。)

https://msdn.microsoft.com/en-us/library/cc673027%28v=vs.110%29.aspx

从上面的链接,相关的信息是这个代码示例:

 public static void Main() { // Create a new dictionary of strings, with string keys, and // access it through the generic ICollection interface. The // generic ICollection interface views the dictionary as a // collection of KeyValuePair objects with the same type // arguments as the dictionary. // ICollection> openWith = new Dictionary(); // Add some elements to the dictionary. When elements are // added through the ICollection interface, the keys // and values must be wrapped in KeyValuePair objects. // openWith.Add(new KeyValuePair("txt", "notepad.exe")); openWith.Add(new KeyValuePair("bmp", "paint.exe")); openWith.Add(new KeyValuePair("dib", "paint.exe")); openWith.Add(new KeyValuePair("rtf", "wordpad.exe")); ... } 

可以看出,创建了一个Dictionary类型的新对象并称为openWith 。 然后创建一个新的KVP对象,并使用.Add方法将其添加到openWith

真的有人真的应该这样做是扩展

  public static void Add(this IDictionary dic, KeyValuePair KVP) { dic.Add(KVP.Key, KVP.Value); } 

但如果没有真正的需要,我建议不要这样做

只是因为Dictionary类的枚举器返回KeyValuePair,并不意味着它是如何在内部实现的。

如果你真的需要通过KVP,请使用IDictionary,因为你已经以这种格式获得了它们。 否则使用赋值或只使用Add方法。

将它作为扩展添加到项目中会出现什么问题?

 namespace System.Collection.Generic { public static class DictionaryExtensions { public static void AddKeyValuePair(this IDictionary me, KeyValuePair other) { me.Add(other.Key, other.Value); } } } 

我不是100%肯定,但我认为Dictionary的内部实现是一个哈希表,这意味着键被转换为哈希以执行快速查找。

如果您想了解更多有关哈希表的信息,请阅读此处

http://en.wikipedia.org/wiki/Hash_table