Hashtable Clase

Definición

Representa una colección de pares de clave y valor que se organizan por código hash de la clave.

public ref class Hashtable : System::Collections::IDictionary
public ref class Hashtable : ICloneable, System::Collections::IDictionary, System::Runtime::Serialization::IDeserializationCallback, System::Runtime::Serialization::ISerializable
public class Hashtable : System.Collections.IDictionary
public class Hashtable : ICloneable, System.Collections.IDictionary, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
[System.Serializable]
public class Hashtable : ICloneable, System.Collections.IDictionary, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class Hashtable : ICloneable, System.Collections.IDictionary, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
type Hashtable = class
    interface ICollection
    interface IEnumerable
    interface IDictionary
type Hashtable = class
    interface ICollection
    interface IEnumerable
    interface IDictionary
    interface ICloneable
    interface IDeserializationCallback
    interface ISerializable
type Hashtable = class
    interface ICollection
    interface IEnumerable
    interface IDictionary
    interface ISerializable
    interface IDeserializationCallback
    interface ICloneable
[<System.Serializable>]
type Hashtable = class
    interface IDictionary
    interface ICollection
    interface IEnumerable
    interface ISerializable
    interface IDeserializationCallback
    interface ICloneable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type Hashtable = class
    interface IDictionary
    interface ICollection
    interface IEnumerable
    interface ISerializable
    interface IDeserializationCallback
    interface ICloneable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type Hashtable = class
    interface IDictionary
    interface ISerializable
    interface IDeserializationCallback
    interface ICloneable
    interface ICollection
    interface IEnumerable
Public Class Hashtable
Implements IDictionary
Public Class Hashtable
Implements ICloneable, IDeserializationCallback, IDictionary, ISerializable
Herencia
Hashtable
Derivado
Atributos
Implementaciones

Ejemplos

En el ejemplo siguiente se muestra cómo crear, inicializar y realizar varias funciones en y Hashtable cómo imprimir sus claves y valores.

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
#>

Comentarios

Cada elemento es un par clave-valor almacenado en un DictionaryEntry objeto . Una clave no puede ser null, pero un valor puede ser .

Importante

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

Los objetos usados como claves por un Hashtable son necesarios para invalidar el Object.GetHashCode método (o la IHashCodeProvider interfaz) y el Object.Equals método (o la IComparer interfaz). La implementación de ambos métodos e interfaces debe controlar la distinción entre mayúsculas y minúsculas de la misma manera; de lo contrario, Hashtable podría comportarse incorrectamente. Por ejemplo, al crear un Hashtable, debe usar la CaseInsensitiveHashCodeProvider clase (o cualquier implementación que no IHashCodeProvider distingue mayúsculas de minúsculas) con la CaseInsensitiveComparer clase (o cualquier implementación que no IComparer distingue mayúsculas de minúsculas).

Además, estos métodos deben generar los mismos resultados cuando se llama con los mismos parámetros mientras la clave existe en .Hashtable Una alternativa es usar un Hashtable constructor con un IEqualityComparer parámetro . Si la igualdad de clave era simplemente igualdad de referencia, la implementación heredada de Object.GetHashCode y Object.Equals bastaría.

Los objetos de clave deben ser inmutables siempre que se usen como claves en .Hashtable

Cuando se agrega un elemento a Hashtable, el elemento se coloca en un cubo basado en el código hash de la clave. Las búsquedas posteriores de la clave usan el código hash de la clave para buscar solo en un cubo determinado, lo que reduce sustancialmente el número de comparaciones de claves necesarias para buscar un elemento.

El factor de carga de un Hashtable determina la relación máxima de elementos con los depósitos. Los factores de carga más pequeños provocan tiempos de búsqueda promedio más rápidos a costa del aumento del consumo de memoria. El factor de carga predeterminado de 1,0 generalmente proporciona el mejor equilibrio entre velocidad y tamaño. También se puede especificar un factor de carga diferente cuando se crea .Hashtable

A medida que se agregan elementos a , Hashtableaumenta el factor de carga real de Hashtable . Cuando el factor de carga real alcanza el factor de carga especificado, el número de cubos de Hashtable se incrementa automáticamente al número primo más pequeño que es mayor que el doble del número actual de Hashtable cubos.

Cada objeto de clave de Hashtable debe proporcionar su propia función hash, a la que se puede tener acceso mediante una llamada a GetHash. Sin embargo, cualquier objeto que implemente IHashCodeProvider se puede pasar a un Hashtable constructor y esa función hash se usa para todos los objetos de la tabla.

La capacidad de un Hashtable es el número de elementos que Hashtable puede contener. A medida que se agregan elementos a , Hashtablela capacidad aumenta automáticamente según sea necesario mediante la reasignación.

Solo .NET Framework: En el caso de objetos muy grandesHashtable, puede aumentar la capacidad máxima a 2 mil millones de elementos en un sistema de 64 bits estableciendo el enabled atributo del elemento true de <gcAllowVeryLargeObjects> configuración en en el entorno en tiempo de ejecución.

La foreach instrucción del lenguaje C# (For Each en Visual Basic) devuelve un objeto del tipo de los elementos de la colección. Dado que cada elemento de Hashtable 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. Por ejemplo:

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

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

Dado que la serialización y deserialización de un enumerador para un Hashtable puede hacer que los elementos se vuelvan a ordenar, no es posible continuar la enumeración sin llamar al Reset método .

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 .

Constructores

Hashtable()

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial, el factor de carga, el proveedor de código hash y el comparador predeterminados.

Hashtable(IDictionary)

Inicializa una nueva instancia de la clase Hashtable copiando los elementos del diccionario especificado en el nuevo objeto Hashtable. El nuevo objeto Hashtable tiene una capacidad inicial igual al número de elementos copiados, y utiliza el factor de carga, el proveedor de código hash y comparador predeterminados.

Hashtable(IDictionary, IEqualityComparer)

Inicializa una nueva instancia de la clase Hashtable copiando los elementos del diccionario especificado en un nuevo objeto Hashtable. El nuevo objeto Hashtable tiene una capacidad inicial igual al número de elementos copiados, y utiliza el factor de carga predeterminado y el objeto IEqualityComparer especificado.

Hashtable(IDictionary, IHashCodeProvider, IComparer)
Obsoletos.
Obsoletos.

Inicializa una nueva instancia de la clase Hashtable copiando los elementos del diccionario especificado en el nuevo objeto Hashtable. El nuevo objeto Hashtable tiene una capacidad inicial igual al número de elementos copiados, utiliza el factor de carga predeterminado, y el proveedor de código hash y comparador especificados. Esta API está obsoleta. Para una alternativa, vea Hashtable(IDictionary, IEqualityComparer).

Hashtable(IDictionary, Single)

Inicializa una nueva instancia de la clase Hashtable copiando los elementos del diccionario especificado en el nuevo objeto Hashtable. El nuevo objeto Hashtable tiene una capacidad inicial igual al número de elementos copiados, utiliza el factor de carga especificado, y el proveedor de código hash y comparador predeterminados.

Hashtable(IDictionary, Single, IEqualityComparer)

Inicializa una nueva instancia de la clase Hashtable copiando los elementos del diccionario especificado en el nuevo objeto Hashtable. El nuevo objeto Hashtable tiene una capacidad inicial igual al número de elementos copiados, y utiliza el factor de carga y el objeto IEqualityComparer especificados.

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

Inicializa una nueva instancia de la clase Hashtable copiando los elementos del diccionario especificado en el nuevo objeto Hashtable. El nuevo objeto Hashtable tiene una capacidad inicial igual al número de elementos copiados, y utiliza el factor de carga, el proveedor de código hash y el comparador especificados.

Hashtable(IEqualityComparer)

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial y el factor de carga predeterminados, y el objeto IEqualityComparer especificado.

Hashtable(IHashCodeProvider, IComparer)
Obsoletos.
Obsoletos.
Obsoletos.

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial y el factor de carga predeterminados, y el proveedor de código hash y el comparador especificados.

Hashtable(Int32)

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial especificada, y el factor de carga, el proveedor de código hash y el comparador predeterminados.

Hashtable(Int32, IEqualityComparer)

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial y el objeto IEqualityComparer especificados, y el factor de carga predeterminado.

Hashtable(Int32, IHashCodeProvider, IComparer)
Obsoletos.
Obsoletos.

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial, el proveedor de código hash y el comparador especificados, y el factor de carga predeterminado.

Hashtable(Int32, Single)

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial y el factor de carga especificados, y el proveedor de código hash y el comparador predeterminados.

Hashtable(Int32, Single, IEqualityComparer)

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial, el factor de carga y el objeto IEqualityComparer especificados.

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

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial, el factor de carga, el proveedor de código hash y el comparador especificados.

Hashtable(SerializationInfo, StreamingContext)

Inicializa una nueva instancia vacía de la clase Hashtable que es serializable, utilizando los objetos SerializationInfo y StreamingContext especificados.

Propiedades

comparer
Obsoletos.
Obsoletos.

Obtiene o establece el IComparer que se utilizará para Hashtable.

Count

Obtiene el número de pares clave-valor incluidos en Hashtable.

EqualityComparer

Obtiene el IEqualityComparer que se va a utilizar para Hashtable.

hcp
Obsoletos.
Obsoletos.

Obtiene o establece el objeto que puede dispensar códigos hash.

IsFixedSize

Obtiene un valor que indica si la interfaz Hashtable tiene un tamaño fijo.

IsReadOnly

Obtiene un valor que indica si Hashtable es de solo lectura.

IsSynchronized

Obtiene un valor que indica si el acceso a la interfaz Hashtable está sincronizado (es seguro para subprocesos).

Item[Object]

Obtiene o establece el valor asociado a la clave especificada.

Keys

Obtiene una interfaz ICollection que contiene las claves de Hashtable.

SyncRoot

Obtiene un objeto que se puede usar para sincronizar el acceso a Hashtable.

Values

Obtiene una interfaz ICollection que contiene los valores de la interfaz Hashtable.

Métodos

Add(Object, Object)

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

Clear()

Quita todos los elementos de Hashtable.

Clone()

Crea una copia superficial de la colección Hashtable.

Contains(Object)

Determina si Hashtable contiene una clave específica.

ContainsKey(Object)

Determina si Hashtable contiene una clave específica.

ContainsValue(Object)

Determina si Hashtable contiene un valor específico.

CopyTo(Array, Int32)

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

Equals(Object)

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

(Heredado de Object)
GetEnumerator()

Devuelve un objeto IDictionaryEnumerator que itera a través del objeto Hashtable.

GetHash(Object)

Devuelve el código hash de la clave especificada.

GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetObjectData(SerializationInfo, StreamingContext)

Implementa la interfaz de ISerializable y devuelve los datos necesarios para serializar Hashtable.

GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
KeyEquals(Object, Object)

Compara un Object específico con una clave concreta en Hashtable.

MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
OnDeserialization(Object)

Implementa la interfaz ISerializable y genera el evento de deserialización cuando esta ha finalizado.

Remove(Object)

Quita el elemento con la clave especificada de Hashtable.

Synchronized(Hashtable)

Devuelve un contenedor sincronizado (seguro para subprocesos) para el objeto Hashtable.

ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Implementaciones de interfaz explícitas

IEnumerable.GetEnumerator()

Devuelve un enumerador que recorre en iteración una colección.

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

Seguridad para subprocesos

Hashtable es seguro para subprocesos para su uso por varios subprocesos de lector y un único subproceso de escritura. Es seguro para subprocesos de uso multiproceso cuando solo uno de los subprocesos realiza operaciones de escritura (actualización), lo que permite lecturas sin bloqueo siempre que los escritores se serialicen en .Hashtable Para admitir varios escritores, todas las operaciones de Hashtable deben realizarse a través del contenedor devuelto por el Synchronized(Hashtable) método , siempre que no haya ningún subproceso leyendo el Hashtable objeto.

La enumeración a través de 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