代码之家  ›  专栏  ›  技术社区  ›  David Schmitt

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

  •  12
  • David Schmitt  · 技术社区  · 16 年前

    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”个参数

    为什么会这样?

    3 回复  |  直到 11 年前
        1
  •  18
  •   Marc Gravell    16 年前

    预期的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}
    }
    

    它使用 添加(键、值) 方法。

        2
  •  9
  •   Pop Catalin    16 年前

    实现了一些接口方法 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
  •  0
  •   Daniel A.A. Pelsmaeker    12 年前

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

    IDictionary<K、 V>; 来源于 ICollection<键值对<K、 V>;> .

    推荐文章