2008-11-06 71 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

相关问题