【问题标题】:C#: How can Dictionary<K,V> implement ICollection<KeyValuePair<K,V>> without having Add(KeyValuePair<K,V>)?C#:Dictionary<K,V> 如何在没有 Add(KeyValuePair<K,V>) 的情况下实现 ICollection<KeyValuePair<K,V>>?
【发布时间】:2010-09-21 01:12:14
【问题描述】:

System.Collections.Generic.Dictionary&lt;TKey, TValue&gt;,它显然实现了ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;,但没有所需的“void Add(KeyValuePair&lt;TKey, TValue&gt; item)”功能。

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

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

失败了

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

为什么会这样?

【问题讨论】:

  • {new KeyValuePair("muh", 2)}

标签: c# .net dictionary interface


【解决方案1】:

预期的 API 是通过两个参数添加 Add(key,value) 方法(或 this[key] 索引器);因此,它使用显式接口实现来提供Add(KeyValuePair&lt;,&gt;) 方法。

如果您改用IDictionary&lt;string, int&gt; 接口,您将可以访问缺少的方法(因为您无法在接口上隐藏任何内容)。

此外,对于集合初始化器,请注意您可以使用替代语法:

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

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

【讨论】:

  • 天啊,早该知道的!
【解决方案2】:

一些接口方法实现了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();

【讨论】:

    【解决方案3】:

    它不直接实现ICollection&lt;KeyValuePair&lt;K,V&gt;&gt;。它实现了IDictionary&lt;K,V&gt;

    IDictionary&lt;K,V&gt; 派生自 ICollection&lt;KeyValuePair&lt;K,V&gt;&gt;

    【讨论】:

    • 这并不能真正回答问题 - 它必须(有效)仍然具有这样的 Add 方法 - 它恰好是一个显式实现而不是公共类 API。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    相关资源
    最近更新 更多