Hashtable Hashtable Hashtable Hashtable Class

Definição

Representa uma coleção de pares chave-valor organizados com base no código hash da chave.Represents a collection of key/value pairs that are organized based on the hash code of the key.

public ref class Hashtable : ICloneable, System::Collections::IDictionary, System::Runtime::Serialization::IDeserializationCallback, System::Runtime::Serialization::ISerializable
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class Hashtable : ICloneable, System.Collections.IDictionary, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
type Hashtable = class
    interface IDictionary
    interface ISerializable
    interface IDeserializationCallback
    interface ICloneable
    interface ICollection
    interface IEnumerable
Public Class Hashtable
Implements ICloneable, IDeserializationCallback, IDictionary, ISerializable
Herança
HashtableHashtableHashtableHashtable
Derivado
Atributos
Implementações

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.The following example shows how to create, initialize and perform various functions to a Hashtable and how to print out its keys and values.

using namespace System;
using namespace System::Collections;

public ref class Example
{
public:
    static void Main()
    {
        // Create a new hash table.
        //
        Hashtable^ openWith = gcnew 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();
        for each( 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();
        for each( 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();
        for each( 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.");
        }
    }
};

int main()
{
    Example::Main();
}

/* 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.
 */
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.
 */
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.
# Create new hash table using PowerShell syntax
$OpenWith = @{}

# Add one element to the hash table using the Add method
$OpenWith.Add('txt', 'notepad.exe')

# Add three eleements using PowerShell syntax three different ways
$OpenWith.dib = 'paint.exe'

$KeyBMP = 'bmp'
$OpenWith[$KeyBMP] = 'paint.exe'

$OpenWith += @{'rtf' = 'wordpad.exe'}

# Display hash table
"There are {0} in the `$OpenWith hash table as follows:" -f $OpenWith.Count
''

# Display hashtable properties
'Count of items in the hashtable  : {0}' -f $OpenWith.Count
'Is hashtable fixed size?         : {0}' -f $OpenWith.IsFixedSize
'Is hashtable read-only?          : {0}' -f $OpenWith.IsReadonly
'Is hashtabale synchronised?      : {0}' -f $OpenWith.IsSynchronized
''
'Keys in hashtable:'
$OpenWith.Keys
''
'Values in hashtable:'
$OpenWith.Values
''

<#
This script produces the following output:

There are 4 in the $OpenWith hash table as follows:

Name                           Value                                                                            
----                           -----                                                                            
txt                            notepad.exe                                                                      
dib                            paint.exe                                                                        
bmp                            paint.exe                                                                        
rtf                            wordpad.exe                                                                      

Count of items in the hashtable  : 4
Is hashtable fixed size?         : False
Is hashtable read-only?          : False
Is hashtabale synchronised?      : False

Keys in hashtable:
txt
dib
bmp
rtf

Values in hashtable:
notepad.exe
paint.exe
paint.exe
wordpad.exe
#>

Comentários

Cada elemento é um par de chave/valor armazenado em DictionaryEntry um objeto.Each element is a key/value pair stored in a DictionaryEntry object. Uma chave não pode nullser, mas um valor pode ser.A key cannot be null, but a value can be.

Importante

Não recomendamos que você use a Hashtable classe para o novo desenvolvimento.We don't recommend that you use the Hashtable class for new development. Em vez disso, recomendamos que você use Dictionary<TKey,TValue> a classe genérica.Instead, we recommend that you use the generic Dictionary<TKey,TValue> class. Para obter mais informações, consulte coleções não genéricas não devem ser usadas no github.For more information, see Non-generic collections shouldn't be used on GitHub.

Os objetos usados como chaves por um Hashtable são necessários para substituir o Object.GetHashCode método (ou a IHashCodeProvider interface) e o Object.Equals método (ou a IComparer interface).The objects used as keys by a Hashtable are required to override the Object.GetHashCode method (or the IHashCodeProvider interface) and the Object.Equals method (or the IComparer interface). A implementação de ambos os métodos e interfaces deve lidar com a diferenciação de maiúsculas e minúsculas da mesma forma; caso contrário, Hashtable o pode se comportar incorretamente.The implementation of both methods and interfaces must handle case sensitivity the same way; otherwise, the Hashtable might behave incorrectly. Por exemplo, ao criar um Hashtable, você deve usar a CaseInsensitiveHashCodeProvider classe (ou IHashCodeProvider qualquer implementação que não diferencia maiúsculas de minúsculas) com a CaseInsensitiveComparer classe (ou qualquer IComparer implementação que não diferencia maiúsculas de minúsculas).For example, when creating a Hashtable, you must use the CaseInsensitiveHashCodeProvider class (or any case-insensitive IHashCodeProvider implementation) with the CaseInsensitiveComparer class (or any case-insensitive IComparer implementation).

Além disso, esses métodos devem produzir os mesmos resultados quando chamados com os mesmos parâmetros, enquanto a chave existe Hashtableno.Furthermore, these methods must produce the same results when called with the same parameters while the key exists in the Hashtable. Uma alternativa é usar um Hashtable Construtor com um IEqualityComparer parâmetro.An alternative is to use a Hashtable constructor with an IEqualityComparer parameter. Se a igualdade de chave fosse simplesmente a igualdade de referência, Object.GetHashCode a Object.Equals implementação herdada de e seria suficiente.If key equality were simply reference equality, the inherited implementation of Object.GetHashCode and Object.Equals would suffice.

Os objetos de chave devem ser imutáveis contanto que sejam usados como chaves no Hashtable.Key objects must be immutable as long as they are used as keys in the Hashtable.

Quando um elemento é adicionado ao Hashtable, o elemento é colocado em um Bucket com base no código hash da chave.When an element is added to the Hashtable, the element is placed into a bucket based on the hash code of the key. As pesquisas subsequentes da chave usam o código hash da chave para pesquisar em apenas um Bucket específico, reduzindo substancialmente o número de comparações de chave necessárias para encontrar um elemento.Subsequent lookups of the key use the hash code of the key to search in only one particular bucket, thus substantially reducing the number of key comparisons required to find an element.

O fator de carga de Hashtable um determina a proporção máxima de elementos para buckets.The load factor of a Hashtable determines the maximum ratio of elements to buckets. Fatores de carga menores causam tempos de pesquisa média mais rápidos no custo do aumento do consumo de memória.Smaller load factors cause faster average lookup times at the cost of increased memory consumption. O fator de carga padrão de 1,0 geralmente fornece o melhor equilíbrio entre velocidade e tamanho.The default load factor of 1.0 generally provides the best balance between speed and size. Um fator de carga diferente também pode ser especificado quando Hashtable o é criado.A different load factor can also be specified when the Hashtable is created.

À medida que os elementos são Hashtableadicionados a um, o fator de Hashtable carga real dos aumentos.As elements are added to a Hashtable, the actual load factor of the Hashtable increases. Quando o fator de carga real atinge o fator de carga especificado, o número de buckets Hashtable no é aumentado automaticamente para o menor número de primo que é maior que o dobro do Hashtable número atual de buckets.When the actual load factor reaches the specified load factor, the number of buckets in the Hashtable is automatically increased to the smallest prime number that is larger than twice the current number of Hashtable buckets.

Cada objeto de chave no Hashtable deve fornecer sua própria função de hash, que pode ser acessada chamando. GetHashEach key object in the Hashtable must provide its own hash function, which can be accessed by calling GetHash. No entanto, qualquer IHashCodeProvider objeto que implemente pode Hashtable ser passado para um construtor e essa função de hash é usada para todos os objetos na tabela.However, any object implementing IHashCodeProvider can be passed to a Hashtable constructor, and that hash function is used for all objects in the table.

A capacidade de um Hashtable é o número de elementos que Hashtable o pode conter.The capacity of a Hashtable is the number of elements the Hashtable can hold. À medida que os elementos são Hashtableadicionados a um, a capacidade é aumentada automaticamente conforme necessário por meio de realocação.As elements are added to a Hashtable, the capacity is automatically increased as required through reallocation.

Somente .NET Framework: Para objetos muito Hashtable grandes, você pode aumentar a capacidade máxima para 2.000.000.000 elementos em um sistema de 64 bits definindo o enabled atributo do elemento de <gcAllowVeryLargeObjects> configuração para true no ambiente de tempo de execução..NET Framework only: For very large Hashtable objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the enabled attribute of the <gcAllowVeryLargeObjects> configuration element to true in the run-time environment.

A foreach instrução do C# idioma (For Each em Visual Basic) retorna um objeto do tipo dos elementos na coleção.The foreach statement of the C# language (For Each in Visual Basic) returns an object of the type of the elements in the collection. Como cada elemento de Hashtable é um par chave/valor, o tipo de elemento não é o tipo da chave ou o tipo do valor.Since each element of the Hashtable is a key/value pair, the element type is not the type of the key or the type of the value. Em vez disso, o tipo DictionaryEntryde elemento é.Instead, the element type is DictionaryEntry. Por exemplo:For example:

for each(DictionaryEntry de in myHashtable)
{
    // ...
}
foreach(DictionaryEntry de in myHashtable)
{
    // ...
}
For Each de As DictionaryEntry In myHashtable
    ' ...
Next de

A foreach instrução é um wrapper em volta do enumerador, que permite somente a leitura, não a coleção.The foreach statement is a wrapper around the enumerator, which only allows reading from, not writing to, the collection.

Como a serialização e desserialização de um enumerador para um Hashtable pode fazer com que os elementos se tornem reordenados, não é possível continuar a enumeração sem chamar o Reset método.Because serializing and deserializing an enumerator for a Hashtable can cause the elements to become reordered, it is not possible to continue enumeration without calling the Reset method.

Observação

Como as chaves podem ser herdadas e seu comportamento alterado, sua exclusividade absoluta não pode ser garantida por comparações usando o Equals método.Because keys can be inherited and their behavior changed, their absolute uniqueness cannot be guaranteed by comparisons using the Equals method.

Construtores

Hashtable() Hashtable() Hashtable() Hashtable()

Inicializa uma instância nova e vazia da classe Hashtable usando a capacidade inicial, o fator de carga, o provedor de código hash e o comparador padrão.Initializes a new, empty instance of the Hashtable class using the default initial capacity, load factor, hash code provider, and comparer.

Hashtable(IDictionary) Hashtable(IDictionary) Hashtable(IDictionary) Hashtable(IDictionary)

Inicializa uma nova instância da classe Hashtable copiando os elementos do dicionário especificado para o novo objeto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. O novo objeto Hashtable tem uma capacidade inicial igual ao número de elementos copiados e usa o fator de carga, o provedor de código hash e o comparador padrão.The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the default load factor, hash code provider, and comparer.

Hashtable(IDictionary, IEqualityComparer) Hashtable(IDictionary, IEqualityComparer) Hashtable(IDictionary, IEqualityComparer) Hashtable(IDictionary, IEqualityComparer)

Inicializa uma nova instância da classe Hashtable copiando os elementos do dicionário especificado para um novo objeto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to a new Hashtable object. O novo objeto Hashtable tem uma capacidade inicial igual ao número de elementos copiados e usa o fator de carga padrão e o objeto IEqualityComparer especificado.The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the default load factor and the specified IEqualityComparer object.

Hashtable(IDictionary, IHashCodeProvider, IComparer) Hashtable(IDictionary, IHashCodeProvider, IComparer) Hashtable(IDictionary, IHashCodeProvider, IComparer) Hashtable(IDictionary, IHashCodeProvider, IComparer)

Inicializa uma nova instância da classe Hashtable copiando os elementos do dicionário especificado para o novo objeto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. O novo objeto Hashtable tem uma capacidade inicial igual ao número de elementos copiados e usa o fator de carga padrão e o provedor de código hash e o comparador especificados.The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the default load factor, and the specified hash code provider and comparer. Esta API está obsoleta.This API is obsolete. Para obter uma alternativa, consulte Hashtable(IDictionary, IEqualityComparer).For an alternative, see Hashtable(IDictionary, IEqualityComparer).

Hashtable(IDictionary, Single) Hashtable(IDictionary, Single) Hashtable(IDictionary, Single) Hashtable(IDictionary, Single)

Inicializa uma nova instância da classe Hashtable copiando os elementos do dicionário especificado para o novo objeto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. O novo objeto Hashtable tem uma capacidade inicial igual ao número de elementos copiados e usa o fator de carga especificado e o provedor de código hash e o comparador padrão.The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the specified load factor, and the default hash code provider and comparer.

Hashtable(IDictionary, Single, IEqualityComparer) Hashtable(IDictionary, Single, IEqualityComparer) Hashtable(IDictionary, Single, IEqualityComparer) Hashtable(IDictionary, Single, IEqualityComparer)

Inicializa uma nova instância da classe Hashtable copiando os elementos do dicionário especificado para o novo objeto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. O novo objeto Hashtable tem uma capacidade inicial igual ao número de elementos copiados e usa o fator de carga especificado e o objeto IEqualityComparer.The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the specified load factor and IEqualityComparer object.

Hashtable(IDictionary, Single, IHashCodeProvider, IComparer) Hashtable(IDictionary, Single, IHashCodeProvider, IComparer) Hashtable(IDictionary, Single, IHashCodeProvider, IComparer) Hashtable(IDictionary, Single, IHashCodeProvider, IComparer)

Inicializa uma nova instância da classe Hashtable copiando os elementos do dicionário especificado para o novo objeto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. O novo objeto Hashtable tem uma capacidade inicial igual ao número de elementos copiados e usa o fator de carga, o provedor de código hash e o comparador especificados.The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the specified load factor, hash code provider, and comparer.

Hashtable(IEqualityComparer) Hashtable(IEqualityComparer) Hashtable(IEqualityComparer) Hashtable(IEqualityComparer)

Inicializa uma instância nova e vazia da classe Hashtable usando a capacidade inicial e o fator de carga padrão e o objeto IEqualityComparer especificado.Initializes a new, empty instance of the Hashtable class using the default initial capacity and load factor, and the specified IEqualityComparer object.

Hashtable(IHashCodeProvider, IComparer) Hashtable(IHashCodeProvider, IComparer) Hashtable(IHashCodeProvider, IComparer) Hashtable(IHashCodeProvider, IComparer)

Inicializa uma instância nova e vazia da classe Hashtable usando a capacidade inicial e o fator de carga padrão, bem como o provedor de código hash e o comparador especificados.Initializes a new, empty instance of the Hashtable class using the default initial capacity and load factor, and the specified hash code provider and comparer.

Hashtable(Int32) Hashtable(Int32) Hashtable(Int32) Hashtable(Int32)

Inicializa uma instância nova e vazia da classe Hashtable usando a capacidade inicial especificada e o fator de carga padrão, o provedor de código hash e o comparador.Initializes a new, empty instance of the Hashtable class using the specified initial capacity, and the default load factor, hash code provider, and comparer.

Hashtable(Int32, IEqualityComparer) Hashtable(Int32, IEqualityComparer) Hashtable(Int32, IEqualityComparer) Hashtable(Int32, IEqualityComparer)

Inicializa uma instância nova e vazia da classe Hashtable usando a capacidade inicial especificada e IEqualityComparer, bem como o fator de carga padrão.Initializes a new, empty instance of the Hashtable class using the specified initial capacity and IEqualityComparer, and the default load factor.

Hashtable(Int32, IHashCodeProvider, IComparer) Hashtable(Int32, IHashCodeProvider, IComparer) Hashtable(Int32, IHashCodeProvider, IComparer) Hashtable(Int32, IHashCodeProvider, IComparer)

Inicializa uma instância nova e vazia da classe Hashtable usando a capacidade inicial especificada, o provedor de código hash, o comparador e o fator de carga padrão.Initializes a new, empty instance of the Hashtable class using the specified initial capacity, hash code provider, comparer, and the default load factor.

Hashtable(Int32, Single) Hashtable(Int32, Single) Hashtable(Int32, Single) Hashtable(Int32, Single)

Inicializa uma instância nova e vazia da classe Hashtable usando a capacidade inicial e o fator de carga especificados, bem como o provedor de código hash e o comparador padrão.Initializes a new, empty instance of the Hashtable class using the specified initial capacity and load factor, and the default hash code provider and comparer.

Hashtable(Int32, Single, IEqualityComparer) Hashtable(Int32, Single, IEqualityComparer) Hashtable(Int32, Single, IEqualityComparer) Hashtable(Int32, Single, IEqualityComparer)

Inicializa uma instância nova e vazia da classe Hashtable usando a capacidade inicial especificada, o fator de carga e o objeto IEqualityComparer.Initializes a new, empty instance of the Hashtable class using the specified initial capacity, load factor, and IEqualityComparer object.

Hashtable(Int32, Single, IHashCodeProvider, IComparer) Hashtable(Int32, Single, IHashCodeProvider, IComparer) Hashtable(Int32, Single, IHashCodeProvider, IComparer) Hashtable(Int32, Single, IHashCodeProvider, IComparer)

Inicializa uma instância nova e vazia da classe Hashtable usando a capacidade inicial, o fator de carga, o provedor de código hash e o comparador especificados.Initializes a new, empty instance of the Hashtable class using the specified initial capacity, load factor, hash code provider, and comparer.

Hashtable(SerializationInfo, StreamingContext) Hashtable(SerializationInfo, StreamingContext) Hashtable(SerializationInfo, StreamingContext) Hashtable(SerializationInfo, StreamingContext)

Inicializa uma nova instância vazia da classe Hashtable que pode ser serializada usando os objetos SerializationInfo e StreamingContext especificados.Initializes a new, empty instance of the Hashtable class that is serializable using the specified SerializationInfo and StreamingContext objects.

Propriedades

comparer comparer comparer comparer

Obtém ou define o IComparer a ser usado para o Hashtable.Gets or sets the IComparer to use for the Hashtable.

Count Count Count Count

Obtém o número de pares chave-valor contidos no Hashtable.Gets the number of key/value pairs contained in the Hashtable.

EqualityComparer EqualityComparer EqualityComparer EqualityComparer

Obtém o IEqualityComparer a ser usado para o Hashtable.Gets the IEqualityComparer to use for the Hashtable.

hcp hcp hcp hcp

Obtém ou define o objeto que pode dispensar códigos hash.Gets or sets the object that can dispense hash codes.

IsFixedSize IsFixedSize IsFixedSize IsFixedSize

Obtém um valor que indica se o Hashtable tem um tamanho fixo.Gets a value indicating whether the Hashtable has a fixed size.

IsReadOnly IsReadOnly IsReadOnly IsReadOnly

Obtém um valor que indica se o Hashtable é somente leitura.Gets a value indicating whether the Hashtable is read-only.

IsSynchronized IsSynchronized IsSynchronized IsSynchronized

Obtém um valor que indica se o acesso à Hashtable é sincronizado (thread-safe).Gets a value indicating whether access to the Hashtable is synchronized (thread safe).

Item[Object] Item[Object] Item[Object] Item[Object]

Obtém ou define o valor associado à chave especificada.Gets or sets the value associated with the specified key.

Keys Keys Keys Keys

Obtém uma ICollection que contém as chaves na Hashtable.Gets an ICollection containing the keys in the Hashtable.

SyncRoot SyncRoot SyncRoot SyncRoot

Obtém um objeto que pode ser usado para sincronizar o acesso ao Hashtable.Gets an object that can be used to synchronize access to the Hashtable.

Values Values Values Values

Obtém um ICollection que contém os valores no Hashtable.Gets an ICollection containing the values in the Hashtable.

Métodos

Add(Object, Object) Add(Object, Object) Add(Object, Object) Add(Object, Object)

Adiciona um elemento com a chave e o valor especificados ao Hashtable.Adds an element with the specified key and value into the Hashtable.

Clear() Clear() Clear() Clear()

Remove todos os elementos do Hashtable.Removes all elements from the Hashtable.

Clone() Clone() Clone() Clone()

Cria uma cópia superficial do Hashtable.Creates a shallow copy of the Hashtable.

Contains(Object) Contains(Object) Contains(Object) Contains(Object)

Determina se a Hashtable contém uma chave específica.Determines whether the Hashtable contains a specific key.

ContainsKey(Object) ContainsKey(Object) ContainsKey(Object) ContainsKey(Object)

Determina se a Hashtable contém uma chave específica.Determines whether the Hashtable contains a specific key.

ContainsValue(Object) ContainsValue(Object) ContainsValue(Object) ContainsValue(Object)

Determinará se o Hashtable contiver um valor específico.Determines whether the Hashtable contains a specific value.

CopyTo(Array, Int32) CopyTo(Array, Int32) CopyTo(Array, Int32) CopyTo(Array, Int32)

Copia os elementos Hashtable para uma instância Array unidimensional no índice especificado.Copies the Hashtable elements to a one-dimensional Array instance at the specified index.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

Retorna um IDictionaryEnumerator que itera pelo Hashtable.Returns an IDictionaryEnumerator that iterates through the Hashtable.

GetHash(Object) GetHash(Object) GetHash(Object) GetHash(Object)

Retorna o código hash da chave especificada.Returns the hash code for the specified key.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

Implementa a interface ISerializable e retorna os dados necessários para serializar o Hashtable.Implements the ISerializable interface and returns the data needed to serialize the Hashtable.

GetType() GetType() GetType() GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Inherited from Object)
KeyEquals(Object, Object) KeyEquals(Object, Object) KeyEquals(Object, Object) KeyEquals(Object, Object)

Compara um Object específico com uma chave específica no Hashtable.Compares a specific Object with a specific key in the Hashtable.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Inherited from Object)
OnDeserialization(Object) OnDeserialization(Object) OnDeserialization(Object) OnDeserialization(Object)

Implementa a interface ISerializable e gera o evento de desserialização quando a desserialização for concluída.Implements the ISerializable interface and raises the deserialization event when the deserialization is complete.

Remove(Object) Remove(Object) Remove(Object) Remove(Object)

Remove o elemento com a chave especificada do Hashtable.Removes the element with the specified key from the Hashtable.

Synchronized(Hashtable) Synchronized(Hashtable) Synchronized(Hashtable) Synchronized(Hashtable)

Retorna um wrapper sincronizado (thread-safe) para o Hashtable.Returns a synchronized (thread-safe) wrapper for the Hashtable.

ToString() ToString() ToString() ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Inherited from Object)

Implantações explícitas de interface

IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator()

Retorna um enumerador que itera em uma coleção.Returns an enumerator that iterates through a collection.

Métodos de Extensão

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

Converte os elementos de um IEnumerable para o tipo especificado.Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable)

Filtra os elementos de um IEnumerable com base em um tipo especificado.Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

Habilita a paralelização de uma consulta.Enables parallelization of a query.

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable)

Converte um IEnumerable em um IQueryable.Converts an IEnumerable to an IQueryable.

Aplica-se a

Acesso thread-safe

Hashtableo thread é seguro para uso por vários threads de leitor e um único thread de gravação.Hashtable is thread safe for use by multiple reader threads and a single writing thread. É thread-safe para uso de vários threads quando apenas um dos threads executa operações de gravação (atualização), o que permite a leitura livre de bloqueios, desde que os Hashtablegravadores sejam serializados para o.It is thread safe for multi-thread use when only one of the threads perform write (update) operations, which allows for lock-free reads provided that the writers are serialized to the Hashtable. Para dar suporte a vários gravadores Hashtable Synchronized(Hashtable) , todas as operações no devem ser feitas por meio do wrapper retornado pelo método, desde que não haja Hashtable threads lendo o objeto.To support multiple writers all operations on the Hashtable must be done through the wrapper returned by the Synchronized(Hashtable) method, provided that there are no threads reading the Hashtable object.

A enumeração por meio de uma coleção é intrinsecamente não um procedimento de thread seguro.Enumerating through a collection is intrinsically not a thread safe procedure. 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.Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. 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.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.

Veja também