Why the dictionary does not implement Add (KeyValuePair)

IDictionary<TKey, TValue>continues from the interface ICollection<KeyValuePair<TKey, TValue>>, so it has a method Add(KeyValuePair<TKey, TValue> item):

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

However, although it Dictionary<TKey, Tvalue>implements IDictionary<TKey, TValue>, it does not have this overload function:

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

How can it be?

+4
source share
2 answers

As you can see in the documentation and in the link source , it Dictionary<TKey, TValue>explicitly implements this part of the interface ICollection<KeyValuePair<TKey, TValue>>.

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

As you have discovered, you can only call it by clicking on IDictionary<TKey, TValue>or ICollection<KeyValuePair<TKey, TValue>>.

, .

+5

Add Visual Studio, , ICollection<T>

enter image description here

, http://referencesource.microsoft.com/, , ICollection<T> .

#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

+1

Source: https://habr.com/ru/post/1656399/


All Articles