Hashtable 类

定义

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

示例

下面的示例演示如何创建、初始化和执行 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.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
#>

注解

每个元素都是存储在 @no__t 0 对象中的键/值对。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.

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

此外,当用相同的参数调用时,这些方法必须生成相同的结果,而键存在于 Hashtable 中。Furthermore, these methods must produce the same results when called with the same parameters while the key exists in the Hashtable. 一种替代方法是将 Hashtable 构造函数与 @no__t 参数一起使用。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.

密钥对象必须是不可变的,只要它们用作 Hashtable 中的密钥。Key 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.

@No__t 的负载系数确定了元素与存储桶的最大比率。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 时,@no__t 的实际加载因子将增加。As elements are added to a Hashtable, the actual load factor of the Hashtable increases. 当实际加载因子达到指定的负载因子时,Hashtable 中的存储桶数将自动增加到大于当前 @no__t 1 存储桶数两倍的最小质数。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.

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

@No__t 的容量为 Hashtable 可以容纳的元素数。The capacity of a Hashtable is the number of elements the Hashtable can hold. 向 @no__t 添加元素时,会根据需要通过重新分配自动增加容量。As elements are added to a Hashtable, the capacity is automatically increased as required through reallocation.

仅 .NET Framework: 对于非常大的 @no__t 0 对象,可以通过在运行时环境中将@no__t 3配置元素的 @no__t 属性设置为 true,将64位系统上的最大容量增加到2000000000个元素。.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.

C#语言的 @no__t 的语句(Visual Basic 中 For Each)返回集合中元素的类型的对象。The foreach statement of the C# language (For Each in Visual Basic) returns an object of the type of the elements in the collection. 由于 @no__t 的每个元素都是一个键/值对,因此元素类型不是键的类型或值的类型。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

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

由于对 @no__t 的枚举器进行序列化和反序列化可能导致元素重新排序,因此不能在不调用 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 类的新的空实例。Initializes a new, empty instance of the Hashtable class using the default initial capacity, load factor, hash code provider, and comparer.

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 对象中,初始化 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 对象中,初始化 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 对象中,初始化 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 对象中,初始化 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 对象中,初始化 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 类的新的空实例。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 类的新的空实例。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 类的新的空实例。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 以及默认的加载因子来初始化 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 类的新的空实例。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 类的新的空实例。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 对象来初始化 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 类的新的空实例。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 类的新的空实例,该实例可序列化且使用指定的 SerializationInfoStreamingContextInitializes a new, empty instance of the Hashtable class that is serializable using the specified SerializationInfo and StreamingContext objects.

属性

comparer

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

Count

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

EqualityComparer

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

hcp

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

IsFixedSize

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

IsReadOnly

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

IsSynchronized

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

Item[Object]

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

Keys

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

SyncRoot

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

Values

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

方法

Add(Object, Object)

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

Clear()

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

Clone()

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

Contains(Object)

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

ContainsKey(Object)

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

ContainsValue(Object)

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

CopyTo(Array, Int32)

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

Equals(Object)

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

(继承自 Object)
GetEnumerator()

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

GetHash(Object)

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

GetHashCode()

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

(继承自 Object)
GetObjectData(SerializationInfo, StreamingContext)

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

GetType()

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

(继承自 Object)
KeyEquals(Object, Object)

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

MemberwiseClone()

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

(继承自 Object)
OnDeserialization(Object)

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

Remove(Object)

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

Synchronized(Hashtable)

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

ToString()

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

(继承自 Object)

显式界面实现

IEnumerable.GetEnumerator()

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

扩展方法

Cast<TResult>(IEnumerable)

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

OfType<TResult>(IEnumerable)

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

AsParallel(IEnumerable)

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

AsQueryable(IEnumerable)

IEnumerable 转换为 IQueryableConverts an IEnumerable to an IQueryable.

适用于

线程安全性

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

另请参阅