Este é um conteúdo traduzido por máquina.
Biblioteca de classes do .NET Framework
Classe Hashtable

Representa uma coleção de pares de chave/valor que são organizados com base no código hash da chave.

Namespace:  System.Collections
Assembly:  mscorlib (em mscorlib. dll)
Sintaxe

Visual Basic (Declaração)
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class Hashtable _
    Implements IDictionary, ICollection, IEnumerable, ISerializable,  _
    IDeserializationCallback, ICloneable
Visual Basic (Uso)
Dim instance As Hashtable
C#
[SerializableAttribute]
[ComVisibleAttribute(true)]
public class Hashtable : IDictionary, ICollection, 
    IEnumerable, ISerializable, IDeserializationCallback, ICloneable
Visual C++
[SerializableAttribute]
[ComVisibleAttribute(true)]
public ref class Hashtable : IDictionary, 
    ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable
JScript
public class Hashtable implements IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable
Comentários

Cada elemento é uma chave/valor em par guardados no objeto DictionaryEntry Uma chave não pode ser nullNothingnullptruma referência nula (Nada no Visual Basic), mas pode ser um valor.

Os objetos usados como chaves por um Hashtable são necessárias para substituir o método Object..::.GetHashCode (ou a interface IHashCodeProvider) e o método Object..::.Equals (ou a interface IComparer). A implementação de ambos os métodos e interfaces deve tratar maiúscminúsc sensibilidade da mesma maneira; Caso contrário, a Hashtable pode se comportar de forma incorreta. Por exemplo, ao criar um Hashtable, você deve usar a classe CaseInsensitiveHashCodeProvider (ou qualquer implementação não diferencia maiúscminúsc de minúsculas IHashCodeProvider ) com a classe CaseInsensitiveComparer (ou qualquer implementação não diferencia maiúscminúsc de minúsculas IComparer).

Ademais, esses métodos devem produzir os mesmos resultados quando chamado com os mesmos parâmetros enquanto a chave existir no Hashtable. Uma alternativa é usar um construtor Hashtable com um parâmetro IEqualityComparer. Se chave igualdade fosse simplesmente igualdade de referência, a implementação herdada de Object..::.GetHashCode e Object..::.Equals deve ser suficiente.

Objetos chaves devem ser imutáveis, desde que elas são usadas como chaves no Hashtable.

Quando um elemento é adicionado ao Hashtable, o elemento for colocado em uma transmissão baseia a código hash da chave. Pesquisas subseqüentes da chave de usar o código hash da chave para pesquisar somente um compartimento específico, em, portanto, reduzindo significativamente o número de comparações chaves necessários para localizar um elemento.

O fator de carregar de um Hashtable determina a taxa máxima de elementos para compartimentos de memória. Fatores de menor carga podem causar mais rapidamente a pesquisa média de horas no custo de consumo de memória maior. O fator de carregamento padrão de 1,0 geralmente fornece o melhor equilíbrio entre velocidade e tamanho. Um fator de carga diferentes também pode ser especificado quando o Hashtable é criado.

Como os elementos são adicionados a um Hashtable, aumenta a carga do fator real do Hashtable. Quando o fator de carga real atinge o fator de carregamento especificado, o número de compartimentos de memória no Hashtable é aumentado automaticamente para o Muito Pequeno número " Prime " que é Grande que duas vezes o número atual de Hashtable compartimentos de memória.

Cada objeto de chave de Hashtable deve fornecer seu próprio função de hash, que pode ser acessado por chamada GetHash. No entanto, qualquer objeto implementando IHashCodeProvider podem ser passados para um construtor Hashtable e que função de hash é usado para Tudo objetos na tabela.

A capacidade de um Hashtable é o número de elementos que de Hashtable pode conter. Como os elementos são adicionados a um Hashtable, a capacidade é aumentada automaticamente conforme necessário por meio de realocação.

vb#c#

A instrução do C# foreach Idioma (for each na Visual Basic) requer o tipo de cada elemento na coleção. Como cada elemento do Hashtable é um par chave/valor, o tipo de elemento não é o tipo de chave ou o tipo do valor. Em vez disso, o tipo de elemento é DictionaryEntry. Por exemplo:

C#
foreach (DictionaryEntry de in myHashtable) {...}
Visual Basic
For Each de as DictionaryEntry In myHashtable
   ...
Next de
vb#c#

A instrução foreach é um invólucro o enumerador, que permite apenas ler a partir de, não gravar, a coleção.

Como serialização e desserialização de um enumerador para um Hashtable podem causar os elementos para se tornar reordenadas, não é possível continuar a enumeração sem chamar o método Reset.

ObservaçãoObservação:

Porque as chaves podem ser herdadas e seu comportamento alterado, seus Absoluto exclusividade não pode ser garantida por comparações usando o Método Equals.

Exemplos

O exemplo a seguir mostra como criar, inicializar e executar várias funções para um Hashtable e como imprimir suas chaves e valores.

Visual Basic
Imports System
Imports System.Collections

Module Example

    Sub Main()

        ' Create a new hash table.
        '
        Dim openWith As New Hashtable()

        ' Add some elements to the hash table. There are no 
        ' duplicate keys, but some of the values are duplicates.
        openWith.Add("txt", "notepad.exe")
        openWith.Add("bmp", "paint.exe")
        openWith.Add("dib", "paint.exe")
        openWith.Add("rtf", "wordpad.exe")

        ' The Add method throws an exception if the new key is 
        ' already in the hash table.
        Try
            openWith.Add("txt", "winword.exe")
        Catch
            Console.WriteLine("An element with Key = ""txt"" already exists.")
        End Try

        ' The Item property is the default property, so you 
        ' can omit its name when accessing elements. 
        Console.WriteLine("For key = ""rtf"", value = {0}.", _
            openWith("rtf"))

        ' The default Item property can be used to change the value
        ' associated with a key.
        openWith("rtf") = "winword.exe"
        Console.WriteLine("For key = ""rtf"", value = {0}.", _
            openWith("rtf"))

        ' If a key does not exist, setting the default Item property
        ' for that key adds a new key/value pair.
        openWith("doc") = "winword.exe"

        ' ContainsKey can be used to test keys before inserting 
        ' them.
        If Not openWith.ContainsKey("ht") Then
            openWith.Add("ht", "hypertrm.exe")
            Console.WriteLine("Value added for key = ""ht"": {0}", _
                openWith("ht"))
        End If

        ' When you use foreach to enumerate hash table elements,
        ' the elements are retrieved as KeyValuePair objects.
        Console.WriteLine()
        For Each de As DictionaryEntry In openWith
            Console.WriteLine("Key = {0}, Value = {1}", _
                de.Key, de.Value)
        Next de

        ' To get the values alone, use the Values property.
        Dim valueColl As ICollection = openWith.Values

        ' The elements of the ValueCollection are strongly typed
        ' with the type that was specified for hash table values.
        Console.WriteLine()
        For Each s As String In valueColl
            Console.WriteLine("Value = {0}", s)
        Next s

        ' To get the keys alone, use the Keys property.
        Dim keyColl As ICollection = openWith.Keys

        ' The elements of the KeyCollection are strongly typed
        ' with the type that was specified for hash table keys.
        Console.WriteLine()
        For Each s As String In keyColl
            Console.WriteLine("Key = {0}", s)
        Next s

        ' Use the Remove method to remove a key/value pair.
        Console.WriteLine(vbLf + "Remove(""doc"")")
        openWith.Remove("doc")

        If Not openWith.ContainsKey("doc") Then
            Console.WriteLine("Key ""doc"" is not found.")
        End If

    End Sub

End Module

' This code example produces the following output:
'
'An element with Key = "txt" already exists.
'For key = "rtf", value = wordpad.exe.
'For key = "rtf", value = winword.exe.
'Value added for key = "ht": hypertrm.exe
'
'Key = dib, Value = paint.exe
'Key = txt, Value = notepad.exe
'Key = ht, Value = hypertrm.exe
'Key = bmp, Value = paint.exe
'Key = rtf, Value = winword.exe
'Key = doc, Value = winword.exe
'
'Value = paint.exe
'Value = notepad.exe
'Value = hypertrm.exe
'Value = paint.exe
'Value = winword.exe
'Value = winword.exe
'
'Key = dib
'Key = txt
'Key = ht
'Key = bmp
'Key = rtf
'Key = doc
'
'Remove("doc")
'Key "doc" is not found.
C#
using System;
using System.Collections;

class Example
{
    public static void Main()
    {
        // Create a new hash table.
        //
        Hashtable openWith = new Hashtable();

        // Add some elements to the hash table. There are no 
        // duplicate keys, but some of the values are duplicates.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");

        // The Add method throws an exception if the new key is 
        // already in the hash table.
        try
        {
            openWith.Add("txt", "winword.exe");
        }
        catch
        {
            Console.WriteLine("An element with Key = \"txt\" already exists.");
        }

        // The Item property is the default property, so you 
        // can omit its name when accessing elements. 
        Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);

        // The default Item property can be used to change the value
        // associated with a key.
        openWith["rtf"] = "winword.exe";
        Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);

        // If a key does not exist, setting the default Item property
        // for that key adds a new key/value pair.
        openWith["doc"] = "winword.exe";

        // ContainsKey can be used to test keys before inserting 
        // them.
        if (!openWith.ContainsKey("ht"))
        {
            openWith.Add("ht", "hypertrm.exe");
            Console.WriteLine("Value added for key = \"ht\": {0}", openWith["ht"]);
        }

        // When you use foreach to enumerate hash table elements,
        // the elements are retrieved as KeyValuePair objects.
        Console.WriteLine();
        foreach( DictionaryEntry de in openWith )
        {
            Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
        }

        // To get the values alone, use the Values property.
        ICollection valueColl = openWith.Values;

        // The elements of the ValueCollection are strongly typed
        // with the type that was specified for hash table values.
        Console.WriteLine();
        foreach( string s in valueColl )
        {
            Console.WriteLine("Value = {0}", s);
        }

        // To get the keys alone, use the Keys property.
        ICollection keyColl = openWith.Keys;

        // The elements of the KeyCollection are strongly typed
        // with the type that was specified for hash table keys.
        Console.WriteLine();
        foreach( string s in keyColl )
        {
            Console.WriteLine("Key = {0}", s);
        }

        // Use the Remove method to remove a key/value pair.
        Console.WriteLine("\nRemove(\"doc\")");
        openWith.Remove("doc");

        if (!openWith.ContainsKey("doc"))
        {
            Console.WriteLine("Key \"doc\" is not found.");
        }
    }
}

/* This code example produces the following output:

An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Value added for key = "ht": hypertrm.exe

Key = dib, Value = paint.exe
Key = txt, Value = notepad.exe
Key = ht, Value = hypertrm.exe
Key = bmp, Value = paint.exe
Key = rtf, Value = winword.exe
Key = doc, Value = winword.exe

Value = paint.exe
Value = notepad.exe
Value = hypertrm.exe
Value = paint.exe
Value = winword.exe
Value = winword.exe

Key = dib
Key = txt
Key = ht
Key = bmp
Key = rtf
Key = doc

Remove("doc")
Key "doc" is not found.
 */
Hierarquia de herança

System..::.Object
  System.Collections..::.Hashtable
    System.Configuration..::.SettingsAttributeDictionary
    System.Configuration..::.SettingsContext
    System.Data..::.PropertyCollection
    System.Printing.IndexedProperties..::.PrintPropertyDictionary
Segurança de Segmentos

Hashtable é Thread seguro para uso por múltiplos Threads do leitor e um Thread simples de escrita. Ele é segmento seguro para uso multi-thread quando somente um dos segmentos de realizar operações de Gravar (atualização), que permite Bloquear - livre leituras desde que os gravadores são serializados para o Hashtable. Para oferecer suporte a Múltiplo gravadores Tudo as operações a Hashtable devem ser feitas por meio do invólucro retornado pelo méTudo Synchronized , desde que não há nenhum thread ler o objeto Hashtable.

Enumerando a classificação através de um conjunto não é intrinsecamente um procedimento seguro de segmento. Mesmo quando uma coleção é sincronizada, outros Threads poderá ainda modificar a coleção, que faz com que o enumerador para gerar uma exceção. Para garantir segurança de segmentos durante enumeração, você pode bloquear a coleção durante a enumeração inteira ou pegar as exceções resultantes de alterações feitas por outros segmentos.

Plataformas

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, O Windows CE, Windows Mobile para Smartphone, Windows Mobile para Pocket PC, Xbox 360

O .NET Framework e .NET Compact Framework não suporte para todas as versões de cada plataforma. Para obter uma lista das versões com suporte, consulte Requisitos de sistema do .NET framework.
Informações de versão

.NET Framework

Compatível com: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Compatível com: 3.5, 2.0, 1.0

XNA Framework

Compatível com: , 1.0
Consulte também

Referência

Marcas :


Page view tracker