Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.
Traducción
Inglés

Clase DictionaryBase

 

Publicado: octubre de 2016

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

Espacio de nombres:   System.Collections
Ensamblado:  mscorlib (en mscorlib.dll)


[SerializableAttribute]
[ComVisibleAttribute(true)]
public abstract class DictionaryBase : IDictionary, ICollection, 
	IEnumerable

NombreDescripción
System_CAPS_protmethodDictionaryBase()

Inicializa una nueva instancia de la clase DictionaryBase.

NombreDescripción
System_CAPS_pubpropertyCount

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

System_CAPS_protpropertyDictionary

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

System_CAPS_protpropertyInnerHashtable

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

NombreDescripción
System_CAPS_pubmethodClear()

Borra el contenido de la instancia de DictionaryBase.

System_CAPS_pubmethodCopyTo(Array, Int32)

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

System_CAPS_pubmethodEquals(Object)

Determina si el objeto especificado es igual al objeto actual.(Heredado de Object).

System_CAPS_protmethodFinalize()

Permite que un objeto intente liberar recursos y realizar otras operaciones de limpieza antes de ser reclamado por el recolector de basura. (Heredado de Object).

System_CAPS_pubmethodGetEnumerator()

Devuelve un IDictionaryEnumerator que itera por la instancia de DictionaryBase.

System_CAPS_pubmethodGetHashCode()

Sirve como la función hash predeterminada.(Heredado de Object).

System_CAPS_pubmethodGetType()

Obtiene el Type de la instancia actual.(Heredado de Object).

System_CAPS_protmethodMemberwiseClone()

Crea una copia superficial del Object actual.(Heredado de Object).

System_CAPS_protmethodOnClear()

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

System_CAPS_protmethodOnClearComplete()

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

System_CAPS_protmethodOnGet(Object, Object)

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

System_CAPS_protmethodOnInsert(Object, Object)

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

System_CAPS_protmethodOnInsertComplete(Object, Object)

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

System_CAPS_protmethodOnRemove(Object, Object)

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

System_CAPS_protmethodOnRemoveComplete(Object, Object)

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

System_CAPS_protmethodOnSet(Object, Object, Object)

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

System_CAPS_protmethodOnSetComplete(Object, Object, Object)

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

System_CAPS_protmethodOnValidate(Object, Object)

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

System_CAPS_pubmethodToString()

Devuelve una cadena que representa al objeto actual. (Heredado de Object).

NombreDescripción
System_CAPS_pubinterfaceSystem_CAPS_privmethodIDictionary.Add(Object, Object)

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

System_CAPS_pubinterfaceSystem_CAPS_privmethodIDictionary.Contains(Object)

Determina si DictionaryBase contiene una clave específica.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIDictionary.Remove(Object)

Quita el elemento con la clave especificada de DictionaryBase.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIEnumerable.GetEnumerator()

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

System_CAPS_pubinterfaceSystem_CAPS_privpropertyICollection.IsSynchronized

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

System_CAPS_pubinterfaceSystem_CAPS_privpropertyICollection.SyncRoot

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

System_CAPS_pubinterfaceSystem_CAPS_privpropertyIDictionary.IsFixedSize

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

System_CAPS_pubinterfaceSystem_CAPS_privpropertyIDictionary.IsReadOnly

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

System_CAPS_pubinterfaceSystem_CAPS_privpropertyIDictionary.Item[Object]

Obtiene o establece el valor asociado a la clave especificada.

System_CAPS_pubinterfaceSystem_CAPS_privpropertyIDictionary.Keys

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

System_CAPS_pubinterfaceSystem_CAPS_privpropertyIDictionary.Values

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

NombreDescripción
System_CAPS_pubmethodAsParallel()

Sobrecargado. Habilita la paralelización de una consulta.(Definido por ParallelEnumerable).

System_CAPS_pubmethodAsQueryable()

Sobrecargado. Convierte un IEnumerable para un IQueryable.(Definido por Queryable).

System_CAPS_pubmethodCast<TResult>()

Convierte los elementos de un IEnumerable al tipo especificado.(Definido por Enumerable).

System_CAPS_pubmethodOfType<TResult>()

Filtra los elementos de un IEnumerable basado en un tipo especificado.(Definido por Enumerable).

The foreach statement of the C# language (for each in Visual Basic) returns an object of the type of the elements in the collection. Since each element of the T:System.Collections.DictionaryBase is a key/value pair, the element type is not the type of the key or the type of the value. Instead, the element type is T:System.Collections.DictionaryEntry.

The foreach statement is a wrapper around the enumerator, which only allows reading from, not writing to, the collection.

System_CAPS_noteNota

Because keys can be inherited and their behavior changed, their absolute uniqueness cannot be guaranteed by comparisons using the M:System.Type.Equals(System.Object) method.

Notas para implementadores:

This base class is provided to make it easier for implementers to create a strongly typed custom collection. Implementers are encouraged to extend this base class instead of creating their own.

Members of this base class are protected and are intended to be used through a derived class only.

The following code example implements the T:System.Collections.DictionaryBase class and uses that implementation to create a dictionary of T:System.String keys and values that have a P:System.String.Length of 5 characters or less.

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

*/

Plataforma universal de Windows
Disponible desde 10
.NET Framework
Disponible desde 1.1

Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

This implementation does not provide a synchronized (thread-safe) wrapper for a T:System.Collections.DictionaryBase, but derived classes can create their own synchronized versions of the T:System.Collections.DictionaryBase using the P:System.Collections.ICollection.SyncRoot property.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

Volver al principio
Mostrar: