Hashtable 类
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
表示根据键的哈希代码进行组织的键/值对的集合。
public ref class Hashtable : System::Collections::IDictionarypublic ref class Hashtable : ICloneable, System::Collections::IDictionary, System::Runtime::Serialization::IDeserializationCallback, System::Runtime::Serialization::ISerializablepublic class Hashtable : System.Collections.IDictionarypublic 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.ISerializabletype Hashtable = class
    interface ICollection
    interface IEnumerable
    interface IDictionarytype Hashtable = class
    interface ICollection
    interface IEnumerable
    interface IDictionary
    interface ICloneable
    interface IDeserializationCallback
    interface ISerializabletype 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 ICloneablePublic Class Hashtable
Implements IDictionaryPublic 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 上使用非泛型集合 。
需要由 Hashtable 用作键的对象来替代 Object.GetHashCode 方法 (或 IHashCodeProvider 接口) , Object.Equals 方法 (或 IComparer 接口) 。 方法和接口的实现必须以相同的方式处理区分大小写:否则, Hashtable 的行为可能不正确。 例如,在创建 Hashtable时,必须将 CaseInsensitiveHashCodeProvider 类 (或任何不区分大小写 IHashCodeProvider 的实现) 与 CaseInsensitiveComparer 类 (或任何不区分大小写 IComparer 的实现) 。
此外,当键存在于 中 Hashtable时,使用相同参数调用时,这些方法必须生成相同的结果。 另一 Hashtable 种方法是将构造函数与 参数一 IEqualityComparer 起使用。 如果键相等性只是引用相等性,则 和 Object.Equals 的Object.GetHashCode继承实现就足够了。
键对象必须是不可变的,只要它们用作 中的 Hashtable键。
将 元素添加到 时, Hashtable会根据键的哈希代码将元素放入存储桶中。 密钥的后续查找使用密钥的哈希代码在一个特定存储桶中搜索,从而大大减少了查找元素所需的键比较次数。
的 Hashtable 负载因子确定元素与存储桶的最大比率。 较小的负载因子会导致平均查找时间更快,但代价是内存消耗增加。 默认负载因子 1.0 通常提供速度和大小之间的最佳平衡。 创建 时 Hashtable ,还可以指定不同的负载因子。
当元素添加到 时 Hashtable,的实际负载因子 Hashtable 会增加。 当实际负载因子达到指定的负载因子时,中的 Hashtable 存储桶数将自动增加到大于当前存储桶数两倍的 Hashtable 最小质数。
中的每个 Hashtable 键对象都必须提供其自己的哈希函数,可以通过调用 GetHash来访问该函数。 但是,任何对象实现 IHashCodeProvider 都可以传递给构造 Hashtable 函数,并且该哈希函数将用于表中的所有对象。
的 Hashtable 容量是 可以容纳的元素 Hashtable 数。 将元素添加到 时 Hashtable,容量会根据需要通过重新分配自动增加。
              仅.NET Framework:对于非常大Hashtable的对象,可以通过在运行时环境中将配置元素的 <gcAllowVeryLargeObjects> 属性设置为 enabled ,将 64 位系统上的最大容量增加到 true 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 方法的比较无法保证其绝对唯一性。
构造函数
属性
| comparer | 
				已过时.
			 
				已过时.
			 | 
| Count | 获取包含在 Hashtable 中的键/值对的数目。 | 
| EqualityComparer | 获取要用于 IEqualityComparer 的 Hashtable。 | 
| 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) | |
| Equals(Object) | 确定指定对象是否等于当前对象。(继承自 Object) | 
| GetEnumerator() | 返回循环访问 IDictionaryEnumerator 的 Hashtable。 | 
| GetHash(Object) | 返回指定键的哈希代码。 | 
| GetHashCode() | 作为默认哈希函数。(继承自 Object) | 
| GetObjectData(SerializationInfo, StreamingContext) | 
				已过时.
			 实现 ISerializable 接口,并返回序列化 Hashtable 所需的数据。 | 
| GetType() | 获取当前实例的 Type。(继承自 Object) | 
| KeyEquals(Object, Object) | |
| 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即可进行无锁读取。 若要支持多个编写器, Hashtable 必须通过 方法返回 Synchronized(Hashtable) 的包装器对 执行的所有操作,前提是没有线程读取对象 Hashtable 。
通过集合枚举本质上不是线程安全的过程。 即使某个集合已同步,其他线程仍可以修改该集合,这会导致枚举数引发异常。 若要确保枚举过程中的线程安全性,可以在整个枚举期间锁定集合,或者捕获由其他线程进行的更改所导致的异常。