C#: 如果没有 Add(KeyValuePair<K,V>),那么 Dictionary<K,V> 如何实现 ICollection<KeyValuePair<K,V>> 接口?

12

观察 System.Collections.Generic.Dictionary<TKey, TValue>,它显然实现了ICollection<KeyValuePair<TKey, TValue>>接口,但没有需要的"void Add(KeyValuePair<TKey, TValue> item)"函数。

这也可以在尝试像这样初始化一个Dictionary时看到:

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

出现以下错误:

没有匹配 'Add' 方法的重载接受 '1' 个参数

为什么会这样呢?


{新的KeyValuePair<string,int>("muh", 2)} - prabhakaran
3个回答

19
预期的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) 方法。


哎呀,早该知道了! - David Schmitt

9

一些接口方法被显式实现。如果您使用反射器,您可以看到这些显式实现的方法,它们包括:

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

它没有直接实现ICollection<KeyValuePair<K,V>>。它实现了IDictionary<K,V>

IDictionary<K,V>派生自ICollection<KeyValuePair<K,V>>


那并没有真正回答问题 - 它必须(为了有效)仍然具有这样的Add方法 - 它只是一个显式实现,而不是公共类API的一部分。 - Marc Gravell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接