【问题标题】:How come Dictionary does not implement Add(KeyValuePair)为什么 Dictionary 没有实现 Add(KeyValuePair)
【发布时间】:2016-09-30 17:18:36
【问题描述】:

IDictionary<TKey, TValue> 扩展自接口ICollection<KeyValuePair<TKey, TValue>>,所以它有一个Add(KeyValuePair<TKey, TValue> item) 方法:

IDictionary<string, object> dic = new Dictionary<string, object>();
dic.Add(new KeyValuePair<string, object>("number", 42)); // Compiles fine

不过,Dictionary&lt;TKey, Tvalue&gt;虽然实现了IDictionary&lt;TKey, TValue&gt;,但没有这个方法重载:

Dictionary<string, object> dic = new Dictionary<string, object>();
dic.Add(new KeyValuePair<string, object>("number", 42)); // Does not compile

这怎么可能?

【问题讨论】:

标签: c# .net dictionary interface


【解决方案1】:

正如您在the documentationthe reference source 中看到的,Dictionary&lt;TKey, TValue&gt; 实现了ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt; 接口的这一部分显式

void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) 
{
    Add(keyValuePair.Key, keyValuePair.Value);
}

正如您所发现的,您只能通过转换为 IDictionary&lt;TKey, TValue&gt;ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt; 来调用它。

您可能希望看到 this related question 了解隐式和显式接口实现之间的区别。

【讨论】:

  • 另外,因为您在参考源中找到的任何内容都应视为“实施细节”,可能会发生变化,您也可以在“Explicit Interface Implementations”的官方文档中找到它部分以获得一个强有力的合同,这一事实在未来的版本中不会改变。
  • @ScottChamberlain 好点 - 将在答案中添加指向文档的链接。谢谢。
【解决方案2】:

如果您将鼠标悬停在 Visual Studio 中的 Add 方法上,您将看到此方法来自 ICollection&lt;T&gt;

现在,如果您查看http://referencesource.microsoft.com/,您将看到来自接口ICollection&lt;T&gt; 的这个方法是explicitly implemented

#region ICollection<KeyValuePair<TKey, TValue>> Members

void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> value)
{
    //Contract.Ensures(((ICollection<KeyValuePair<TKey, TValue>>)this).Count == Contract.OldValue(((ICollection<KeyValuePair<TKey, TValue>>)this).Count) + 1);  // not threadsafe
}

这就是为什么 IDictionary 可以使用它而不是 Dictionary 的原因

【讨论】:

    猜你喜欢
    • 2011-10-30
    • 2010-09-21
    • 2011-01-16
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    相关资源
    最近更新 更多