C#:Dictionary <K,V>如何在没有Add(KeyValuePair <K,V>)的情况下实现ICollection <KeyValuePair <K,V >>?

Dav*_*itt 11 .net c# dictionary interface

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)
};
Run Code Online (Sandbox Code Playgroud)

失败了

方法'Add'没有重载需要'1'参数

为什么会这样?

Mar*_*ell 18

期望的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}
}
Run Code Online (Sandbox Code Playgroud)

使用该Add(key,value)方法.


Pop*_*lin 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();
Run Code Online (Sandbox Code Playgroud)