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

需要用來做為索引鍵的物件 Hashtable,才能覆寫 Object.GetHashCode 方法(或 @no__t 2 介面)和 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 時,您必須使用具有 CaseInsensitiveComparer 類別(或任何不區分大小寫的 IComparer 執行)的 CaseInsensitiveHashCodeProvider 類別(或任何不區分大小寫的 IHashCodeProvider 執行)。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. 另一個替代方式是使用具有 IEqualityComparer 參數的 @no__t 0 的函式。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-0 的負載因數會決定元素與值區的最大比例。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 中的值區數目會自動增加到大於目前 @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 0 中的每個索引鍵物件都必須提供自己的雜湊函式,其可透過呼叫 GetHash 來存取。Each key object in the Hashtable must provide its own hash function, which can be accessed by calling GetHash. 不過,任何執行 IHashCodeProvider 的物件都可以傳遞至 @no__t 1 的函式,並將該雜湊函數用於資料表中的所有物件。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-0 的容量是 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 物件,您可以將<gcAllowVeryLargeObjects>設定專案的 enabled 屬性設為執行時間環境中的 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#語言的 foreach 語句(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. 因為 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

@No__t-0 語句是列舉值的包裝函式,只允許讀取和寫入集合。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 類別的空白新執行個體,這個執行個體可序列化,並使用指定的 SerializationInfoStreamingContext 物件。Initializes a new, empty instance of the Hashtable class that is serializable using the specified SerializationInfo and StreamingContext objects.

屬性

comparer comparer comparer comparer

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

將有指定索引鍵和數值的項目加入 HashtableAdds 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 重複的 HashtableReturns 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 的淺層複本 (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)

明確介面實作

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)

IEnumerable 轉換成 IQueryableConverts an IEnumerable to an IQueryable.

適用於

執行緒安全性

Hashtable 是安全線程,可供多個讀取器執行緒和單一寫入執行緒使用。Hashtable is thread safe for use by multiple reader threads and a single writing thread. 當只有其中一個執行緒執行寫入(update)作業時,它會具備執行緒安全,可允許無鎖定讀取,前提是寫入器會序列化為 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. 若要支援多個寫入器,必須透過 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.

另請參閱