字典如何实现Add(KeyValuePair)

时间:2016-09-30 17:18:36

标签: c# .net dictionary interface

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<TKey, Tvalue>实现了IDictionary<TKey, TValue>,但它没有使用此方法重载:

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

这怎么可能?

2 个答案:

答案 0 :(得分:5)

正如您在the documentationthe reference source中看到的那样,Dictionary<TKey, TValue>明确地实现了ICollection<KeyValuePair<TKey, TValue>>接口的这一部分

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

正如您所发现的那样,您只能通过强制转换为IDictionary<TKey, TValue>ICollection<KeyValuePair<TKey, TValue>>来调用它。

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

答案 1 :(得分:1)

如果将鼠标悬停在Visual Studio中的Add方法上,您会看到此方法来自ICollection<T>

enter image description here

现在,如果您查看http://referencesource.microsoft.com/,您会看到界面ICollection<T>中的此方法为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

的原因