Hashtable 类

定义

表示根据键的哈希代码进行组织的键/值对的集合。

public ref class Hashtable : System::Collections::IDictionary
public ref class Hashtable : ICloneable, System::Collections::IDictionary, System::Runtime::Serialization::IDeserializationCallback, System::Runtime::Serialization::ISerializable
public class Hashtable : System.Collections.IDictionary
public class Hashtable : ICloneable, System.Collections.IDictionary, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
[System.Serializable]
public class Hashtable : ICloneable, System.Collections.IDictionary, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class Hashtable : ICloneable, System.Collections.IDictionary, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
type Hashtable = class
    interface ICollection
    interface IEnumerable
    interface IDictionary
type Hashtable = class
    interface ICollection
    interface IEnumerable
    interface IDictionary
    interface ICloneable
    interface IDeserializationCallback
    interface ISerializable
type Hashtable = class
    interface ICollection
    interface IEnumerable
    interface IDictionary
    interface ISerializable
    interface IDeserializationCallback
    interface ICloneable
[<System.Serializable>]
type Hashtable = class
    interface IDictionary
    interface ICollection
    interface IEnumerable
    interface ISerializable
    interface IDeserializationCallback
    interface ICloneable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type Hashtable = class
    interface IDictionary
    interface ICollection
    interface IEnumerable
    interface ISerializable
    interface IDeserializationCallback
    interface ICloneable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type Hashtable = class
    interface IDictionary
    interface ISerializable
    interface IDeserializationCallback
    interface ICloneable
    interface ICollection
    interface IEnumerable
Public Class Hashtable
Implements IDictionary
Public Class Hashtable
Implements ICloneable, IDeserializationCallback, IDictionary, ISerializable
继承
Hashtable
派生
属性
实现

示例

以下示例演示如何创建、初始化和执行各种函数, Hashtable 以及如何输出其键和值。

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

注解

每个元素都是存储在对象中的DictionaryEntry键/值配对。 键不能 null,但值可以是。

重要

不建议将 Hashtable 类用于新开发。 相反,我们建议使用泛型 Dictionary<TKey,TValue> 类。 有关详细信息,请参阅不应在GitHub上使用非泛型集合

重写方法 (或IHashCodeProvider接口) Object.Equals和方法 (或IComparer接口) 需要Object.GetHashCode用作键Hashtable的对象。 方法和接口的实现必须以相同的方式处理区分大小写:否则, Hashtable 可能的行为不正确。 例如,创建 a Hashtable时,必须使用 CaseInsensitiveHashCodeProvider 类 (或任何不区分大小 IHashCodeProvider 写的实现) CaseInsensitiveComparer 类 (或任何不区分大小写 IComparer 的实现) 。

此外,当键存在于键中 Hashtable时,这些方法必须使用相同的参数调用时生成相同的结果。 另一种方法是将 Hashtable 构造函数与参数配合使用 IEqualityComparer 。 如果关键相等只是引用相等性,则继承的 Object.GetHashCode 实现并 Object.Equals 足以满足要求。

键对象必须不可变,只要它们用作键。Hashtable

将元素添加到 Hashtable该元素时,该元素将基于键的哈希代码放入存储桶中。 随后的键查找使用键的哈希代码在一个特定存储桶中搜索,从而大大减少了查找元素所需的键比较数。

元素与存储桶的最大比率决定了负载因子 Hashtable 。 较小的负载因素会导致更快的平均查找时间,代价是内存消耗增加。 默认负载系数 1.0 通常提供速度和大小之间的最佳平衡。 创建时 Hashtable 还可以指定不同的负载因子。

随着元素的 Hashtable添加,增加 Hashtable 的实际负载系数。 当实际负载因子达到指定的负载因子时,中 Hashtable 存储桶的数量会自动增加到大于当前存储桶数 Hashtable 两倍的最小质数。

中的每个键对象 Hashtable 都必须提供自己的哈希函数,可通过调用 GetHash来访问该函数。 但是,任何实现 IHashCodeProvider 的对象都可以传递给 Hashtable 构造函数,该哈希函数用于表中的所有对象。

a Hashtable 的容量是可以保留的元素 Hashtable 数。 随着元素添加到 a Hashtable上,通过重新分配自动增加容量。

仅.NET Framework: 对于非常大Hashtable的对象,可以通过在运行时环境中将enabled配置元素的属性 <gcAllowVeryLargeObjects>设置为true,将 64 位系统上的最大容量增加到 20 亿个元素。

foreach Visual Basic) 中 C# 语言 (For Each的语句返回集合中元素类型的对象。 由于每个Hashtable元素都是键/值配对,因此元素类型不是键的类型或值的类型。 相反,元素类型为 DictionaryEntry. 例如:

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

foreach 语句是枚举器周围的包装器,它只允许从集合中读取(而不是写入)集合。

由于序列化和反序列化枚举 Hashtable 器可能会导致元素重新排序,因此无法继续枚举而不调用 Reset 该方法。

备注

由于可以继承键并更改其行为,因此使用该方法的比较 Equals 无法保证其绝对唯一性。

构造函数

Hashtable()

使用默认的初始容量、加载因子、哈希代码提供程序和比较器来初始化 Hashtable 类的新的空实例。

Hashtable(IDictionary)

通过将指定字典中的元素复制到新的 Hashtable 对象中,初始化 Hashtable 类的一个新实例。 新 Hashtable 对象的初始容量等于复制的元素数,并且使用默认的加载因子、哈希代码提供程序和比较器。

Hashtable(IDictionary, IEqualityComparer)

通过将指定字典中的元素复制到新的 Hashtable 对象中,初始化 Hashtable 类的一个新实例。 新 Hashtable 对象的初始容量等于复制的元素数,并且使用默认加载因子和指定的 IEqualityComparer 对象。

Hashtable(IDictionary, IHashCodeProvider, IComparer)
已过时。
已过时。

通过将指定字典中的元素复制到新的 Hashtable 对象中,初始化 Hashtable 类的一个新实例。 新 Hashtable 对象的初始容量等于复制的元素数,并且使用默认的加载因子、指定的哈希代码提供程序和指定的比较器。 此 API 已废弃不用。 有关另类,请参见 Hashtable(IDictionary, IEqualityComparer)

Hashtable(IDictionary, Single)

通过将指定字典中的元素复制到新的 Hashtable 对象中,初始化 Hashtable 类的一个新实例。 新 Hashtable 对象的初始容量等于复制的元素数,并且使用指定的加载因子、默认哈希代码提供程序和默认比较器。

Hashtable(IDictionary, Single, IEqualityComparer)

通过将指定字典中的元素复制到新的 Hashtable 对象中,初始化 Hashtable 类的一个新实例。 新 Hashtable 对象的初始容量等于复制的元素数,并且使用指定的加载因子和 IEqualityComparer 对象。

Hashtable(IDictionary, Single, IHashCodeProvider, IComparer)
已过时。
已过时。

通过将指定字典中的元素复制到新的 Hashtable 对象中,初始化 Hashtable 类的一个新实例。 新 Hashtable 对象的初始容量等于复制的元素数,并且使用指定的加载因子、哈希代码提供程序和比较器。

Hashtable(IEqualityComparer)

使用默认的初始容量、默认加载因子和指定的 Hashtable 对象来初始化 IEqualityComparer 类的新的空实例。

Hashtable(IHashCodeProvider, IComparer)
已过时。
已过时。
已过时。

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

Hashtable(Int32)

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

Hashtable(Int32, IEqualityComparer)

使用指定的初始容量和 Hashtable 以及默认的加载因子来初始化 IEqualityComparer 类的新的空实例。

Hashtable(Int32, IHashCodeProvider, IComparer)
已过时。
已过时。

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

Hashtable(Int32, Single)

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

Hashtable(Int32, Single, IEqualityComparer)

使用指定的初始容量、加载因子和 Hashtable 对象来初始化 IEqualityComparer 类的新的空实例。

Hashtable(Int32, Single, IHashCodeProvider, IComparer)
已过时。
已过时。

使用指定的初始容量、加载因子、哈希代码提供程序和比较器来初始化 Hashtable 类的新的空实例。

Hashtable(SerializationInfo, StreamingContext)

初始化 Hashtable 类的新的空实例,该实例可序列化且使用指定的 SerializationInfoStreamingContext

属性

comparer
已过时。
已过时。

获取或设置要用于 IComparerHashtable

Count

获取包含在 Hashtable 中的键/值对的数目。

EqualityComparer

获取要用于 IEqualityComparerHashtable

hcp
已过时。
已过时。

获取或设置可分配哈希代码的对象。

IsFixedSize

获取一个值,该值指示 Hashtable 是否具有固定大小。

IsReadOnly

获取一个值,该值指示 Hashtable 是否为只读。

IsSynchronized

获取一个值,该值指示是否同步对 Hashtable 的访问(线程安全)。

Item[Object]

获取或设置与指定的键关联的值。

Keys

获取包含 ICollection 中的键的 Hashtable

SyncRoot

获取可用于同步对 Hashtable 的访问的对象。

Values

获取一个 ICollection,它包含 Hashtable 中的值。

方法

Add(Object, Object)

将带有指定键和值的元素添加到 Hashtable 中。

Clear()

Hashtable 中移除所有元素。

Clone()

创建 Hashtable 的浅表副本。

Contains(Object)

确定 Hashtable 是否包含特定键。

ContainsKey(Object)

确定 Hashtable 是否包含特定键。

ContainsValue(Object)

确定 Hashtable 是否包含特定值。

CopyTo(Array, Int32)

Hashtable 元素复制到一维 Array 实例中的指定索引位置。

Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
GetEnumerator()

返回循环访问 IDictionaryEnumeratorHashtable

GetHash(Object)

返回指定键的哈希代码。

GetHashCode()

作为默认哈希函数。

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

实现 ISerializable 接口,并返回序列化 Hashtable 所需的数据。

GetType()

获取当前实例的 Type

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

将特定 ObjectHashtable 中的特定键进行比较。

MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
OnDeserialization(Object)

实现 ISerializable 接口,并在完成反序列化之后引发反序列化事件。

Remove(Object)

Hashtable 中移除带有指定键的元素。

Synchronized(Hashtable)

返回 Hashtable 的同步(线程安全)包装。

ToString()

返回表示当前对象的字符串。

(继承自 Object)

显式接口实现

IEnumerable.GetEnumerator()

返回循环访问集合的枚举数。

扩展方法

Cast<TResult>(IEnumerable)

IEnumerable 的元素强制转换为指定的类型。

OfType<TResult>(IEnumerable)

根据指定类型筛选 IEnumerable 的元素。

AsParallel(IEnumerable)

启用查询的并行化。

AsQueryable(IEnumerable)

IEnumerable 转换为 IQueryable

适用于

线程安全性

Hashtable 是线程安全的,可供多个读取器线程和单个写入线程使用。 当只有一个线程执行写入 (更新) 操作时,多线程使用线程是线程安全的,前提是编写器序列化为 Hashtable非锁定读取。 若要支持多个编写器,必须在方法返回Synchronized(Hashtable)的包装器中完成所有操作Hashtable,前提是没有读取Hashtable对象的线程。

通过集合进行枚举本质上不是线程安全过程。 即使某个集合已同步,其他线程仍可以修改该集合,这会导致枚举数引发异常。 若要确保枚举过程中的线程安全性,可以在整个枚举期间锁定集合,或者捕获由其他线程进行的更改所导致的异常。

另请参阅