字典如何实现Add(KeyValuePair)

Mat*_*ero 4 .net c# 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
Run Code Online (Sandbox Code Playgroud)

但是,尽管是Dictionary<TKey, Tvalue>implements IDictionary<TKey, TValue>,它没有这个方法重载:

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

怎么会这样?

Cha*_*ger 5

正如您在文档参考源中看到的那样,明确地Dictionary<TKey, TValue>实现了ICollection<KeyValuePair<TKey, TValue>>接口的这一部分.

void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) 
{
    Add(keyValuePair.Key, keyValuePair.Value);
}
Run Code Online (Sandbox Code Playgroud)

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

您可能希望看到有关隐式和显式接口实现之间差异的相关问题.