Ler em inglês

Compartilhar via


DictionaryBase Classe

Definição

Fornece a classe base abstract para uma coleção fortemente tipada de pares chave-valor.

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
Herança
DictionaryBase
Derivado
Atributos
Implementações

Exemplos

O exemplo de código a seguir implementa a DictionaryBase classe e usa essa implementação para criar um dicionário de String chaves e valores que têm um Length de 5 caracteres ou 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

*/

Comentários

Importante

Não recomendamos que você use a DictionaryBase classe para novo desenvolvimento. Em vez disso, recomendamos que você use o genérico Dictionary<TKey,TValue> ou KeyedCollection<TKey,TItem> a classe . Para obter mais informações, consulte Coleções não genéricas não devem ser usadas no GitHub.

A instrução foreach C# e a instrução Visual Basic For Each retornam um objeto do tipo dos elementos na coleção. Como cada elemento do DictionaryBase é um par chave/valor, o tipo de elemento não é o tipo da chave ou o tipo do valor. Em vez disso, o tipo de elemento é DictionaryEntry.

A foreach instrução é um wrapper em torno do enumerador, que só permite a leitura, não a gravação em, a coleção.

Observação

Como as chaves podem ser herdadas e seu comportamento foi alterado, sua exclusividade absoluta não pode ser garantida por comparações usando o Equals método .

Notas aos Implementadores

Essa classe base é fornecida para facilitar a criação de uma coleção personalizada fortemente tipada para os implementadores. Os implementadores são incentivados a estender essa classe base em vez de criar suas próprias.

Os membros dessa classe base são protegidos e devem ser usados apenas por meio de uma classe derivada.

Construtores

DictionaryBase()

Inicializa uma nova instância da classe DictionaryBase.

Propriedades

Count

Obtém o número de elementos contidos na instância de DictionaryBase.

Dictionary

Obtém a lista de elementos contidos na instância DictionaryBase.

InnerHashtable

Obtém a lista de elementos contidos na instância DictionaryBase.

Métodos

Clear()

Limpa o conteúdo da instância DictionaryBase.

CopyTo(Array, Int32)

Copia os elementos DictionaryBase para um objeto Array unidimensional no índice especificado.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetEnumerator()

Retorna um IDictionaryEnumerator que itera pela instância de DictionaryBase.

GetHashCode()

Serve como a função de hash padrão.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
OnClear()

Executa processos adicionais personalizados antes de limpar o conteúdo da instância de DictionaryBase.

OnClearComplete()

Executa processos adicionais personalizados após limpar o conteúdo da instância DictionaryBase.

OnGet(Object, Object)

Obtém o elemento com a chave e o valor especificados à instância de DictionaryBase.

OnInsert(Object, Object)

Executa os processos personalizados adicionais antes de inserir um novo elemento na instância DictionaryBase.

OnInsertComplete(Object, Object)

Executa processos personalizados adicionais após inserir um novo elemento na instância de DictionaryBase.

OnRemove(Object, Object)

Executa processos personalizados adicionais antes de remover um elemento da instância de DictionaryBase.

OnRemoveComplete(Object, Object)

Executa processos personalizados adicionais após remover um elemento da instância de DictionaryBase.

OnSet(Object, Object, Object)

Executa processos personalizados adicionais antes de definir um valor na instância DictionaryBase.

OnSetComplete(Object, Object, Object)

Executa processos personalizados adicionais após configurar um valor na instância de DictionaryBase.

OnValidate(Object, Object)

Executa processos personalizados adicionais ao validar o elemento com a chave e o valor especificados.

ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Implantações explícitas de interface

ICollection.IsSynchronized

Obtém um valor que indica se o acesso a um objeto DictionaryBase é sincronizado (thread-safe).

ICollection.SyncRoot

Obtém um objeto que pode ser usado para sincronizar o acesso a um objeto DictionaryBase.

IDictionary.Add(Object, Object)

Adiciona um elemento com a chave e o valor especificados ao DictionaryBase.

IDictionary.Contains(Object)

Determina se a DictionaryBase contém uma chave específica.

IDictionary.IsFixedSize

Obtém um valor que indica se o objeto DictionaryBase tem um tamanho fixo.

IDictionary.IsReadOnly

Obtém um valor que indica se um objeto DictionaryBase é somente leitura.

IDictionary.Item[Object]

Obtém ou define o valor associado à chave especificada.

IDictionary.Keys

Obtém um objeto ICollection que contém as chaves no objeto DictionaryBase.

IDictionary.Remove(Object)

Remove o elemento com a chave especificada do DictionaryBase.

IDictionary.Values

Obtém um objeto ICollection que contém os valores no objeto DictionaryBase.

IEnumerable.GetEnumerator()

Retorna um IEnumerator que itera pelo DictionaryBase.

Métodos de Extensão

Cast<TResult>(IEnumerable)

Converte os elementos de um IEnumerable para o tipo especificado.

OfType<TResult>(IEnumerable)

Filtra os elementos de um IEnumerable com base em um tipo especificado.

AsParallel(IEnumerable)

Habilita a paralelização de uma consulta.

AsQueryable(IEnumerable)

Converte um IEnumerable em um IQueryable.

Aplica-se a

Produto Versões
.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

Acesso thread-safe

Os membros estáticos públicos (Shared no Visual Basic) desse são thread-safe. Não há garantia de que qualquer membro de instância seja seguro para threads.

Essa implementação não fornece um wrapper sincronizado (thread-safe) para um DictionaryBase, mas as classes derivadas podem criar suas próprias versões sincronizadas do DictionaryBase usando a SyncRoot propriedade .

A enumeração por meio de uma coleção não é um procedimento thread-safe intrínseco. Mesmo quando uma coleção está sincronizada, outros threads ainda podem modificar a coleção, o que faz o enumerador lançar uma exceção. Para garantir thread-safe durante a enumeração, é possível bloquear a coleção durante toda a enumeração ou verificar as exceções resultantes das alterações feitas por outros threads.

Confira também