Hashtable Hashtable Hashtable Hashtable Class

Definition

代表根據索引鍵的雜湊程式碼,所整理的索引鍵/值組集合。 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)]
[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
Inheritance
HashtableHashtableHashtableHashtable
Derived
Attributes
ComVisibleAttribute SerializableAttribute
Implements

Examples

下列範例示範如何建立、 初始化和執行各種功能至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
#>

Remarks

每個項目是儲存在索引鍵/值組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. 相反地,我們建議您先使用一般HashSet<T>類別。Instead, we recommend that you use the generic HashSet<T> 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.

針對非常大型Hashtable物件,您可以藉由設定增加到 64 位元系統上的 2 億個元素的最大容量enabled屬性的組態項目true在執行階段環境中。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 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.

Constructors

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 類別的空白新執行個體,這個執行個體可序列化,並使用指定的 SerializationInfoStreamingContext 物件。 Initializes a new, empty instance of the Hashtable class that is serializable using the specified SerializationInfo and StreamingContext objects.

Properties

comparer comparer comparer comparer

取得或設定 IComparer 所使用的 Hashtable Gets 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

取得 IEqualityComparer 所使用的 Hashtable Gets 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 中的索引鍵的 Hashtable Gets 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.

Methods

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()

傳回透過 IDictionaryEnumerator 重複的 Hashtable Returns 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()

取得目前執行個體的 Type Gets 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 的淺層複本 (Shallow Copy)。 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)

Explicit Interface Implementations

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

傳回逐一查看集合的列舉值。 Returns an enumerator that iterates through a collection.

Applies to

Thread Safety

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. 若要支援多個寫入器上的所有作業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.

See Also