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

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

  •  11
  • 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 回复  |  直到 10 年前
        1
  •  18
  •   Marc Gravell    16 年前

    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 . 如果使用reflector,您可以看到显式实现的方法,这些方法是:

    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> i收集<KeyValuePair<K、 V>&燃气轮机;