Hashtable Hashtable Hashtable Hashtable Class

定义

表示根据键的哈希代码进行组织的键/值对的集合。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
继承
HashtableHashtableHashtableHashtable
派生
属性
实现

示例

下面的示例演示如何创建、 初始化和执行各种功能到Hashtable以及如何打印出其键和值。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
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
#>

注解

每个元素都是键/值对存储在DictionaryEntry对象。Each element is a key/value pair stored in a DictionaryEntry object. 密钥不能为null,但可以是一个值。A key cannot be null, but a value can be.

重要

我们不建议你使用Hashtable类的新的开发。We don't recommend that you use the Hashtable class for new development. 相反,我们建议使用泛型Dictionary<TKey,TValue>类。Instead, we recommend that you use the generic Dictionary<TKey,TValue> class. 有关详细信息,请参阅不应使用非泛型集合GitHub 上。For more information, see Non-generic collections shouldn't be used on GitHub.

作为键,即可通过使用的对象Hashtable需重写Object.GetHashCode方法 (或IHashCodeProvider接口) 和Object.Equals方法 (或IComparer接口)。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). 方法和接口的实现必须处理区分大小写相同的方式;否则为Hashtable行为可能不正确。The implementation of both methods and interfaces must handle case sensitivity the same way; otherwise, the Hashtable might behave incorrectly. 例如,在创建Hashtable,则必须使用CaseInsensitiveHashCodeProvider类 (或任何不区分大小写IHashCodeProvider实现) 与CaseInsensitiveComparer类 (或任何不区分大小写IComparer实现)。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).

此外,这些方法必须生成相同的结果中存在该密钥时,如果使用相同的参数调用时HashtableFurthermore, these methods must produce the same results when called with the same parameters while the key exists in the Hashtable. 一种替代方法是使用Hashtable构造函数使用IEqualityComparer参数。An alternative is to use a Hashtable constructor with an IEqualityComparer parameter. 如果键相等性只是引用相等性的继承的实现Object.GetHashCodeObject.Equals就已经足够了。If key equality were simply reference equality, the inherited implementation of Object.GetHashCode and Object.Equals would suffice.

密钥对象必须是固定不变,只要它们被用作键在HashtableKey objects must be immutable as long as they are used as keys in the Hashtable.

当元素添加到Hashtable,该元素放入存储桶基于键的哈希代码。When an element is added to the Hashtable, the element is placed into a bucket based on the hash code of the key. 密钥的后续查找使用键的哈希代码搜索中只有一个特定的存储桶,这将大大减少查找元素所需的键比较次数。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.

加载因子Hashtable确定元素与存储桶的最大比率。The load factor of a Hashtable determines the maximum ratio of elements to buckets. 较小负载因素会导致更快地平均查找时间但代价是增加的内存消耗。Smaller load factors cause faster average lookup times at the cost of increased memory consumption. 默认加载因子 1.0 通常提供速度和大小之间的最佳平衡。The default load factor of 1.0 generally provides the best balance between speed and size. 也可以是不同的加载因子时指定Hashtable创建。A different load factor can also be specified when the Hashtable is created.

元素添加到Hashtable的实际负载因子Hashtable会增加。As elements are added to a Hashtable, the actual load factor of the Hashtable increases. 在实际的加载因子到达指定的加载因子中的存储桶的数量Hashtable自动增加到大于两次的当前数最小质数Hashtable存储桶。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.

中的每个键对象Hashtable必须提供其自己的哈希函数,可通过调用访问GetHashEach key object in the Hashtable must provide its own hash function, which can be accessed by calling GetHash. 但是,任何对象实现IHashCodeProvider可以传递给Hashtable构造函数和哈希函数用于在表中的所有对象。However, any object implementing IHashCodeProvider can be passed to a Hashtable constructor, and that hash function is used for all objects in the table.

容量Hashtable是元素数目Hashtable可以容纳。The capacity of a Hashtable is the number of elements the Hashtable can hold. 元素添加到Hashtable,自动增加容量通过重新分配所需的方式。As elements are added to a Hashtable, the capacity is automatically increased as required through reallocation.

仅限.NET framework: 对于非常大Hashtable对象,可以通过设置增加到 20 亿元素在 64 位系统上的最大容量enabled的属性 <gcAllowVeryLargeObjects> configuration 元素true中运行时环境。.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.

foreach C# 语言的语句 (For Each在 Visual Basic 中) 返回集合中的元素的类型的对象。The foreach statement of the C# language (For Each in Visual Basic) returns an object of the type of the elements in the collection. 由于每个元素的Hashtable是一个键/值对,元素类型不是键的类型或值的类型。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. 相反,元素类型是DictionaryEntryInstead, the element type is DictionaryEntry. 例如:For example:

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

foreach语句是只允许读取、 不写入集合的枚举器周围的包装。The foreach statement is a wrapper around the enumerator, which only allows reading from, not writing to, the collection.

因为序列化和反序列化的枚举数Hashtable可能会导致要变得重新排序的元素,它不是可以继续运行而无需调用枚举Reset方法。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.

备注

因为密钥可以被继承,但不能更改其行为,使用的比较保证其绝对唯一性Equals方法。Because keys can be inherited and their behavior changed, their absolute uniqueness cannot be guaranteed by comparisons using the Equals method.

构造函数

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

使用默认的初始容量、加载因子、哈希代码提供程序和比较器来初始化 Hashtable 类的新的空实例。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)

通过将指定字典中的元素复制到新的 Hashtable 对象中,初始化 Hashtable 类的一个新实例。Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. Hashtable 对象的初始容量等于复制的元素数,并且使用默认的加载因子、哈希代码提供程序和比较器。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)

通过将指定字典中的元素复制到新的 Hashtable 对象中,初始化 Hashtable 类的一个新实例。Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to a new Hashtable object. Hashtable 对象的初始容量等于复制的元素数,并且使用默认加载因子和指定的 IEqualityComparer 对象。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)

通过将指定字典中的元素复制到新的 Hashtable 对象中,初始化 Hashtable 类的一个新实例。Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. Hashtable 对象的初始容量等于复制的元素数,并且使用默认的加载因子、指定的哈希代码提供程序和指定的比较器。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. 此 API 已过时。This API is obsolete. 有关另类,请参见 Hashtable(IDictionary, IEqualityComparer)For an alternative, see Hashtable(IDictionary, IEqualityComparer).

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

通过将指定字典中的元素复制到新的 Hashtable 对象中,初始化 Hashtable 类的一个新实例。Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. Hashtable 对象的初始容量等于复制的元素数,并且使用指定的加载因子、默认哈希代码提供程序和默认比较器。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)

通过将指定字典中的元素复制到新的 Hashtable 对象中,初始化 Hashtable 类的一个新实例。Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. Hashtable 对象的初始容量等于复制的元素数,并且使用指定的加载因子和 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)

通过将指定字典中的元素复制到新的 Hashtable 对象中,初始化 Hashtable 类的一个新实例。Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. Hashtable 对象的初始容量等于复制的元素数,并且使用指定的加载因子、哈希代码提供程序和比较器。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)

使用默认的初始容量、默认加载因子和指定的 Hashtable 对象来初始化 IEqualityComparer 类的新的空实例。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)

使用默认初始容量、默认加载因子、指定的哈希代码提供程序和指定的比较器来初始化 Hashtable 类的新的空实例。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)

使用指定的初始容量、默认加载因子、默认哈希代码提供程序和默认比较器来初始化 Hashtable 类的新的空实例。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)

使用指定的初始容量和 Hashtable 以及默认的加载因子来初始化 IEqualityComparer 类的新的空实例。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)

使用指定的初始容量、哈希代码提供程序、比较器和默认加载因子来初始化 Hashtable 类的新的空实例。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)

使用指定的初始容量、指定的加载因子、默认的哈希代码提供程序和默认比较器来初始化 Hashtable 类的新的空实例。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)

使用指定的初始容量、加载因子和 Hashtable 对象来初始化 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)

使用指定的初始容量、加载因子、哈希代码提供程序和比较器来初始化 Hashtable 类的新的空实例。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)

初始化 Hashtable 类的新的空实例,该实例可序列化且使用指定的 SerializationInfoStreamingContextInitializes a new, empty instance of the Hashtable class that is serializable using the specified SerializationInfo and StreamingContext objects.

属性

comparer comparer comparer comparer

获取或设置要用于 IComparerHashtableGets or sets the IComparer to use for the Hashtable.

Count Count Count Count

获取包含在 Hashtable 中的键/值对的数目。Gets the number of key/value pairs contained in the Hashtable.

EqualityComparer EqualityComparer EqualityComparer EqualityComparer

获取要用于 IEqualityComparerHashtableGets the IEqualityComparer to use for the Hashtable.

hcp hcp hcp hcp

获取或设置可分配哈希代码的对象。Gets or sets the object that can dispense hash codes.

IsFixedSize IsFixedSize IsFixedSize IsFixedSize

获取一个值,该值指示 Hashtable 是否具有固定大小。Gets a value indicating whether the Hashtable has a fixed size.

IsReadOnly IsReadOnly IsReadOnly IsReadOnly

获取一个值,该值指示 Hashtable 是否为只读。Gets a value indicating whether the Hashtable is read-only.

IsSynchronized IsSynchronized IsSynchronized IsSynchronized

获取一个值,该值指示是否同步对 Hashtable 的访问(线程安全)。Gets a value indicating whether access to the Hashtable is synchronized (thread safe).

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

获取或设置与指定的键关联的值。Gets or sets the value associated with the specified key.

Keys Keys Keys Keys

获取包含 ICollection 中的键的 HashtableGets an ICollection containing the keys in the Hashtable.

SyncRoot SyncRoot SyncRoot SyncRoot

获取可用于同步对 Hashtable 的访问的对象。Gets an object that can be used to synchronize access to the Hashtable.

Values Values Values Values

获取一个 ICollection,它包含 Hashtable 中的值。Gets an ICollection containing the values in the Hashtable.

方法

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

将带有指定键和值的元素添加到 Hashtable 中。Adds an element with the specified key and value into the Hashtable.

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

Hashtable 中移除所有元素。Removes all elements from the Hashtable.

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

创建 Hashtable 的浅表副本。Creates a shallow copy of the Hashtable.

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

确定 Hashtable 是否包含特定键。Determines whether the Hashtable contains a specific key.

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

确定 Hashtable 是否包含特定键。Determines whether the Hashtable contains a specific key.

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

确定 Hashtable 是否包含特定值。Determines whether the Hashtable contains a specific value.

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

Hashtable 元素复制到一维 Array 实例中的指定索引位置。Copies the Hashtable elements to a one-dimensional Array instance at the specified index.

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

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

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

返回循环访问 IDictionaryEnumeratorHashtableReturns an IDictionaryEnumerator that iterates through the Hashtable.

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

返回指定键的哈希代码。Returns the hash code for the specified key.

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

作为默认哈希函数。Serves as the default hash function.

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

实现 ISerializable 接口,并返回序列化 Hashtable 所需的数据。Implements the ISerializable interface and returns the data needed to serialize the Hashtable.

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

获取当前实例的 TypeGets the Type of the current instance.

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

将特定 ObjectHashtable 中的特定键进行比较。Compares a specific Object with a specific key in the Hashtable.

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

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

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

实现 ISerializable 接口,并在完成反序列化之后引发反序列化事件。Implements the ISerializable interface and raises the deserialization event when the deserialization is complete.

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

Hashtable 中移除包含指定键的元素。Removes the element with the specified key from the Hashtable.

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

返回 Hashtable 的同步(线程安全)包装。Returns a synchronized (thread-safe) wrapper for the Hashtable.

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

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)

显式界面实现

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

返回循环访问集合的枚举数。Returns an enumerator that iterates through a collection.

扩展方法

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

IEnumerable 的元素强制转换为指定的类型。Casts the elements of an IEnumerable to the specified type.

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

根据指定类型筛选 IEnumerable 的元素。Filters the elements of an IEnumerable based on a specified type.

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

启用查询的并行化。Enables parallelization of a query.

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

将转换IEnumerableIQueryableConverts an IEnumerable to an IQueryable.

适用于

线程安全性

Hashtable 是线程以供多个读取器线程和一个写入线程安全的。Hashtable is thread safe for use by multiple reader threads and a single writing thread. 它是线程安全的多线程使用时,只有一个线程执行写入 (更新) 操作,从而允许进行无锁读取,前提是编写器序列化为HashtableIt 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. 若要支持多个编写器上的所有操作Hashtable必须通过返回的包装器完成Synchronized(Hashtable)方法,提供没有线程读取Hashtable对象。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.

枚举整个集合本质上不是线程安全的过程。Enumerating through a collection is intrinsically not a thread safe procedure. 即使某个集合已同步,其他线程仍可以修改该集合,这会导致枚举数引发异常。Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. 若要确保枚举过程中的线程安全性,可以在整个枚举期间锁定集合,或者捕获由其他线程进行的更改所导致的异常。To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

另请参阅