example ejemplos c# .net dictionary interface

ejemplos - keyvaluepair c#



C#: ¿Cómo puede Dictionary<K, V> implementar ICollection<KeyValuePair<K, V>> sin tener Add(KeyValuePair<K, V>)? (3)

Mirando System.Collections.Generic.Dictionary<TKey, TValue> , implementa claramente ICollection<KeyValuePair<TKey, TValue>> , pero no tiene la función necesaria " void Add(KeyValuePair<TKey, TValue> item) ".

Esto también se puede ver al intentar inicializar un Dictionary como este:

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

que falla con

Sin sobrecarga para el método ''Agregar'' toma ''1'' argumentos

¿Por qué es así?


Algunos métodos de interfaz se implementan explícitamente . Si usa el reflector, puede ver los métodos implementados explícitamente, que son:

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();


La API esperada es agregar mediante el método de dos argumentos Add(key,value) (o el indexador de this[key] ); como tal, usa una implementación de interfaz explícita para proporcionar el método Add(KeyValuePair<,>) .

Si utiliza la IDictionary<string, int> en su lugar, tendrá acceso al método que falta (ya que no puede ocultar nada en una interfaz).

Además, con el iniciador de la colección, tenga en cuenta que puede usar la sintaxis alternativa:

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

que usa el método Add(key,value) .


No implementa ICollection<KeyValuePair<K,V>> directamente. Implementa IDictionary<K,V> .

IDictionary<K,V> deriva de ICollection<KeyValuePair<K,V>> .