Leer en inglés

Compartir vía


DictionaryBase Clase

Definición

Proporciona la clase base abstract para una colección de pares clave-valor fuertemente tipada.

C#
public abstract class DictionaryBase : System.Collections.IDictionary
C#
[System.Serializable]
public abstract class DictionaryBase : System.Collections.IDictionary
C#
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class DictionaryBase : System.Collections.IDictionary
Herencia
DictionaryBase
Derivado
Atributos
Implementaciones

Ejemplos

En el ejemplo de código siguiente se implementa la DictionaryBase clase y se usa esa implementación para crear un diccionario de String claves y valores que tienen un Length valor de 5 caracteres o menos.

C#
using System;
using System.Collections;

public class ShortStringDictionary : DictionaryBase  {

   public String this[ String key ]  {
      get  {
         return( (String) Dictionary[key] );
      }
      set  {
         Dictionary[key] = value;
      }
   }

   public ICollection Keys  {
      get  {
         return( Dictionary.Keys );
      }
   }

   public ICollection Values  {
      get  {
         return( Dictionary.Values );
      }
   }

   public void Add( String key, String value )  {
      Dictionary.Add( key, value );
   }

   public bool Contains( String key )  {
      return( Dictionary.Contains( key ) );
   }

   public void Remove( String key )  {
      Dictionary.Remove( key );
   }

   protected override void OnInsert( Object key, Object value )  {
      if ( key.GetType() != typeof(System.String) )
        {
            throw new ArgumentException( "key must be of type String.", "key" );
        }
        else  {
         String strKey = (String) key;
         if ( strKey.Length > 5 )
            throw new ArgumentException( "key must be no more than 5 characters in length.", "key" );
      }

      if ( value.GetType() != typeof(System.String) )
        {
            throw new ArgumentException( "value must be of type String.", "value" );
        }
        else  {
         String strValue = (String) value;
         if ( strValue.Length > 5 )
            throw new ArgumentException( "value must be no more than 5 characters in length.", "value" );
      }
   }

   protected override void OnRemove( Object key, Object value )  {
      if ( key.GetType() != typeof(System.String) )
        {
            throw new ArgumentException( "key must be of type String.", "key" );
        }
        else  {
         String strKey = (String) key;
         if ( strKey.Length > 5 )
            throw new ArgumentException( "key must be no more than 5 characters in length.", "key" );
      }
   }

   protected override void OnSet( Object key, Object oldValue, Object newValue )  {
      if ( key.GetType() != typeof(System.String) )
        {
            throw new ArgumentException( "key must be of type String.", "key" );
        }
        else  {
         String strKey = (String) key;
         if ( strKey.Length > 5 )
            throw new ArgumentException( "key must be no more than 5 characters in length.", "key" );
      }

      if ( newValue.GetType() != typeof(System.String) )
        {
            throw new ArgumentException( "newValue must be of type String.", "newValue" );
        }
        else  {
         String strValue = (String) newValue;
         if ( strValue.Length > 5 )
            throw new ArgumentException( "newValue must be no more than 5 characters in length.", "newValue" );
      }
   }

   protected override void OnValidate( Object key, Object value )  {
      if ( key.GetType() != typeof(System.String) )
        {
            throw new ArgumentException( "key must be of type String.", "key" );
        }
        else  {
         String strKey = (String) key;
         if ( strKey.Length > 5 )
            throw new ArgumentException( "key must be no more than 5 characters in length.", "key" );
      }

      if ( value.GetType() != typeof(System.String) )
        {
            throw new ArgumentException( "value must be of type String.", "value" );
        }
        else  {
         String strValue = (String) value;
         if ( strValue.Length > 5 )
            throw new ArgumentException( "value must be no more than 5 characters in length.", "value" );
      }
   }
}

public class SamplesDictionaryBase  {

   public static void Main()  {

      // Creates and initializes a new DictionaryBase.
      ShortStringDictionary mySSC = new ShortStringDictionary();

      // Adds elements to the collection.
      mySSC.Add( "One", "a" );
      mySSC.Add( "Two", "ab" );
      mySSC.Add( "Three", "abc" );
      mySSC.Add( "Four", "abcd" );
      mySSC.Add( "Five", "abcde" );

      // Display the contents of the collection using foreach. This is the preferred method.
      Console.WriteLine( "Contents of the collection (using foreach):" );
      PrintKeysAndValues1( mySSC );

      // Display the contents of the collection using the enumerator.
      Console.WriteLine( "Contents of the collection (using enumerator):" );
      PrintKeysAndValues2( mySSC );

      // Display the contents of the collection using the Keys property and the Item property.
      Console.WriteLine( "Initial contents of the collection (using Keys and Item):" );
      PrintKeysAndValues3( mySSC );

      // Tries to add a value that is too long.
      try  {
         mySSC.Add( "Ten", "abcdefghij" );
      }
      catch ( ArgumentException e )  {
         Console.WriteLine( e.ToString() );
      }

      // Tries to add a key that is too long.
      try  {
         mySSC.Add( "Eleven", "ijk" );
      }
      catch ( ArgumentException e )  {
         Console.WriteLine( e.ToString() );
      }

      Console.WriteLine();

      // Searches the collection with Contains.
      Console.WriteLine( "Contains \"Three\": {0}", mySSC.Contains( "Three" ) );
      Console.WriteLine( "Contains \"Twelve\": {0}", mySSC.Contains( "Twelve" ) );
      Console.WriteLine();

      // Removes an element from the collection.
      mySSC.Remove( "Two" );

      // Displays the contents of the collection.
      Console.WriteLine( "After removing \"Two\":" );
      PrintKeysAndValues1( mySSC );
   }

   // Uses the foreach statement which hides the complexity of the enumerator.
   // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection.
   public static void PrintKeysAndValues1( ShortStringDictionary myCol )  {
      foreach ( DictionaryEntry myDE in myCol )
         Console.WriteLine( "   {0,-5} : {1}", myDE.Key, myDE.Value );
      Console.WriteLine();
   }

   // Uses the enumerator.
   // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection.
   public static void PrintKeysAndValues2( ShortStringDictionary myCol )  {
      DictionaryEntry myDE;
      System.Collections.IEnumerator myEnumerator = myCol.GetEnumerator();
      while ( myEnumerator.MoveNext() )
         if ( myEnumerator.Current != null )  {
            myDE = (DictionaryEntry) myEnumerator.Current;
            Console.WriteLine( "   {0,-5} : {1}", myDE.Key, myDE.Value );
         }
      Console.WriteLine();
   }

   // Uses the Keys property and the Item property.
   public static void PrintKeysAndValues3( ShortStringDictionary myCol )  {
      ICollection myKeys = myCol.Keys;
      foreach ( String k in myKeys )
         Console.WriteLine( "   {0,-5} : {1}", k, myCol[k] );
      Console.WriteLine();
   }
}


/*
This code produces the following output.

Contents of the collection (using foreach):
   Three : abc
   Five  : abcde
   Two   : ab
   One   : a
   Four  : abcd

Contents of the collection (using enumerator):
   Three : abc
   Five  : abcde
   Two   : ab
   One   : a
   Four  : abcd

Initial contents of the collection (using Keys and Item):
   Three : abc
   Five  : abcde
   Two   : ab
   One   : a
   Four  : abcd

System.ArgumentException: value must be no more than 5 characters in length.
Parameter name: value
   at ShortStringDictionary.OnValidate(Object key, Object value)
   at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(Object key, Object value)
   at SamplesDictionaryBase.Main()
System.ArgumentException: key must be no more than 5 characters in length.
Parameter name: key
   at ShortStringDictionary.OnValidate(Object key, Object value)
   at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(Object key, Object value)
   at SamplesDictionaryBase.Main()

Contains "Three": True
Contains "Twelve": False

After removing "Two":
   Three : abc
   Five  : abcde
   One   : a
   Four  : abcd

*/

Comentarios

Importante

No se recomienda usar la DictionaryBase clase para el nuevo desarrollo. En su lugar, se recomienda usar la Dictionary<TKey,TValue> clase genérica o KeyedCollection<TKey,TItem> . Para obtener más información, consulte No se deben usar colecciones no genéricas en GitHub.

La instrucción foreach de C# y la instrucción For Each de Visual Basic devuelven un objeto del tipo de los elementos de la colección. Dado que cada elemento de DictionaryBase es un par clave-valor, el tipo de elemento no es el tipo de la clave o el tipo del valor. En su lugar, el tipo de elemento es DictionaryEntry.

La foreach instrucción es un contenedor alrededor del enumerador, que solo permite leer, no escribir en, la colección.

Nota

Dado que las claves se pueden heredar y cambiar su comportamiento, no se puede garantizar su exclusividad absoluta mediante comparaciones mediante el Equals método .

Notas a los implementadores

Esta clase base se proporciona para facilitar a los implementadores crear una colección personalizada fuertemente tipada. Se recomienda a los implementadores ampliar esta clase base en lugar de crear su propia.

Los miembros de esta clase base están protegidos y están diseñados para usarse únicamente a través de una clase derivada.

Constructores

DictionaryBase()

Inicializa una nueva instancia de la clase DictionaryBase.

Propiedades

Count

Obtiene el número de elementos contenidos en la instancia de DictionaryBase.

Dictionary

Obtiene la lista de elementos incluidos en la instancia de DictionaryBase.

InnerHashtable

Obtiene la lista de elementos incluidos en la instancia de DictionaryBase.

Métodos

Clear()

Borra el contenido de la instancia de DictionaryBase.

CopyTo(Array, Int32)

Copia los elementos de DictionaryBase a una Array unidimensional en el índice especificado.

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
GetEnumerator()

Devuelve un IDictionaryEnumerator que itera por la instancia de DictionaryBase.

GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
OnClear()

Ejecuta procesos personalizados adicionales antes de borrar el contenido de la instancia de DictionaryBase.

OnClearComplete()

Realiza procesos personalizados adicionales después de borrar el contenido de la instancia de DictionaryBase.

OnGet(Object, Object)

Obtiene el elemento con la clave y valor especificados en la instancia de DictionaryBase.

OnInsert(Object, Object)

Realiza procesos personalizados adicionales antes de insertar un nuevo elemento en la instancia de DictionaryBase.

OnInsertComplete(Object, Object)

Realiza procesos personalizados adicionales después de insertar un nuevo elemento en la instancia de DictionaryBase.

OnRemove(Object, Object)

Realiza procesos personalizados adicionales antes de quitar un elemento de la instancia de DictionaryBase.

OnRemoveComplete(Object, Object)

Realiza procesos personalizados adicionales después de quitar un elemento de la instancia de DictionaryBase.

OnSet(Object, Object, Object)

Realiza procesos personalizados adicionales antes de establecer un valor en la instancia de DictionaryBase.

OnSetComplete(Object, Object, Object)

Realiza procesos personalizados adicionales después de establecer un valor en la instancia de DictionaryBase.

OnValidate(Object, Object)

Ejecuta procesos personalizados adicionales al validar el elemento con la clave y valor especificados.

ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Implementaciones de interfaz explícitas

ICollection.IsSynchronized

Obtiene un valor que indica si el acceso a un objeto DictionaryBase está sincronizado (es seguro para subprocesos).

ICollection.SyncRoot

Obtiene un objeto que se puede utilizar para sincronizar el acceso a un objeto DictionaryBase.

IDictionary.Add(Object, Object)

Agrega un elemento con la clave y el valor especificados a DictionaryBase.

IDictionary.Contains(Object)

Determina si DictionaryBase contiene una clave específica.

IDictionary.IsFixedSize

Obtiene un valor que indica si un objeto DictionaryBase tiene un tamaño fijo.

IDictionary.IsReadOnly

Obtiene un valor que indica si un objeto DictionaryBase es de solo lectura.

IDictionary.Item[Object]

Obtiene o establece el valor asociado a la clave especificada.

IDictionary.Keys

Obtiene un objeto ICollection que contiene las claves del objeto DictionaryBase.

IDictionary.Remove(Object)

Quita el elemento con la clave especificada de DictionaryBase.

IDictionary.Values

Obtiene un objeto ICollection que contiene los valores del objeto DictionaryBase.

IEnumerable.GetEnumerator()

Devuelve un objeto IEnumerator que itera a través del objeto DictionaryBase.

Métodos de extensión

Cast<TResult>(IEnumerable)

Convierte los elementos de IEnumerable en el tipo especificado.

OfType<TResult>(IEnumerable)

Filtra los elementos de IEnumerable en función de un tipo especificado.

AsParallel(IEnumerable)

Habilita la paralelización de una consulta.

AsQueryable(IEnumerable)

Convierte una interfaz IEnumerable en IQueryable.

Se aplica a

Producto Versiones
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0

Seguridad para subprocesos

Los miembros estáticos públicos (Shared en Visual Basic) de este tipo son seguros para subprocesos. No se garantiza que los miembros de instancia sean seguros para subprocesos.

Esta implementación no proporciona un contenedor sincronizado (seguro para subprocesos) para una DictionaryBaseclase , pero las clases derivadas pueden crear sus propias versiones sincronizadas de DictionaryBase mediante la SyncRoot propiedad .

Enumerar una colección no es intrínsecamente un procedimiento seguro para subprocesos. Incluso cuando una colección está sincronizada, otros subprocesos todavía pueden modificarla, lo que hace que el enumerador produzca una excepción. Con el fin de garantizar la seguridad para la ejecución de subprocesos durante la enumeración, se puede bloquear la colección durante toda la enumeración o detectar las excepciones resultantes de los cambios realizados por otros subprocesos.

Consulte también