2008-11-06 70 views
11

看着System.Collections.Generic.Dictionary<TKey, TValue>,它清楚地實現了ICollection<KeyValuePair<TKey, TValue>>,但沒有所需的「void Add(KeyValuePair<TKey, TValue> item)」函數。C#:如何在沒有添加(KeyValuePair <K,V>)的情況下實施ICollection <KeyValuePair <K,V>>的字典<K,V>?

這也可以嘗試初始化一個Dictionary這樣,當看到:

private const Dictionary<string, int> PropertyIDs = new Dictionary<string, int>() 
{ 
    new KeyValuePair<string,int>("muh", 2) 
}; 

其失敗

的方法 '添加' 沒有重載採用 '1' 的論點

這是爲什麼呢?

+0

{new KeyValuePair (「muh」,2)} – prabhakaran 2014-03-21 05:58:14

回答

17

預期的API是通過兩個參數Add(key,value)方法(或this[key]索引器)添加;因此,它使用明確的接口實現來提供方法Add(KeyValuePair<,>)

如果您使用IDictionary<string, int>接口,您將有權訪問缺少的方法(因爲您無法在接口上隱藏任何內容)。

此外,在集合初始化,請注意,您可以使用替代語法:

Dictionary<string, int> PropertyIDs = new Dictionary<string, int> { 
    {"abc",1}, {"def",2}, {"ghi",3} 
} 

它使用Add(key,value)方法。

+0

d'oh,應該已經知道了! – 2008-11-06 09:39:43

9

一些接口方法實現了explicitly。如果你使用反射鏡可以看到明確的實施方法,它們是:

void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair); 
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair); 
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index); 
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair); 
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator(); 
void ICollection.CopyTo(Array array, int index); 
void IDictionary.Add(object key, object value); 
bool IDictionary.Contains(object key); 
IDictionaryEnumerator IDictionary.GetEnumerator(); 
void IDictionary.Remove(object key); 
IEnumerator IEnumerable.GetEnumerator(); 
+0

也很高興知道! – 2008-11-06 09:47:34

0

它不直接實現ICollection<KeyValuePair<K,V>>。它實現了IDictionary<K,V>

IDictionary<K,V>來自ICollection<KeyValuePair<K,V>>

+0

這並沒有真正回答這個問題 - 它必須(有效)仍然具有這樣一個Add方法 - 它只是一個明確的實現,而不是公共類API的一部分。 – 2008-11-06 09:56:26

相關問題