C# - Hashtable
Hashtable
是一个非泛型集合,它存储键值对,类似于泛型 `Dictionary
Hashtable 特性
Hashtable
存储键值对。- 属于
System.Collections
命名空间。 - 实现 IDictionary 接口。
- 键必须唯一且不能为 null。
- 值可以为 null 或重复。
- 可以通过在索引器中传递关联键来访问值,例如
myHashtable[key]
- 元素存储为 DictionaryEntry 对象。
创建 Hashtable
以下示例演示如何创建 Hashtable 并添加元素。
示例:创建并添加元素
Hashtable numberNames = new Hashtable();
numberNames.Add(1,"One"); //adding a key/value using the Add() method
numberNames.Add(2,"Two");
numberNames.Add(3,"Three");
//The following throws run-time exception: key already added.
//numberNames.Add(3, "Three");
foreach(DictionaryEntry de in numberNames)
Console.WriteLine("Key: {0}, Value: {1}", de.Key, de.Value);
//creating a Hashtable using collection-initializer syntax
var cities = new Hashtable(){
{"UK", "London, Manchester, Birmingham"},
{"USA", "Chicago, New York, Washington"},
{"India", "Mumbai, New Delhi, Pune"}
};
foreach(DictionaryEntry de in cities)
Console.WriteLine("Key: {0}, Value: {1}", de.Key, de.Value);
Hashtable
集合可以包含 Dictionary 的所有元素,如下所示。
示例:在 Hashtable 中添加 Dictionary
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "one");
dict.Add(2, "two");
dict.Add(3, "three");
Hashtable ht = new Hashtable(dict);
更新 Hashtable
您可以通过在索引器中传递键,从 Hashtable
中检索现有键的值。Hashtable
是非泛型集合,因此在检索值时必须进行类型转换。
示例:更新 Hashtable
//creating a Hashtable using collection-initializer syntax
var cities = new Hashtable(){
{"UK", "London, Manchester, Birmingham"},
{"USA", "Chicago, New York, Washington"},
{"India", "Mumbai, New Delhi, Pune"}
};
string citiesOfUK = (string) cities["UK"]; //cast to string
string citiesOfUSA = (string) cities["USA"]; //cast to string
Console.WriteLine(citiesOfUK);
Console.WriteLine(citiesOfUSA);
cities["UK"] = "Liverpool, Bristol"; // update value of UK key
cities["USA"] = "Los Angeles, Boston"; // update value of USA key
if(!cities.ContainsKey("France")){
cities["France"] = "Paris";
}
移除 Hashtable 中的元素
Remove()
方法移除与 Hashtable
中指定键匹配的键值对。如果 Hashtable 中未找到指定的键,它会抛出 KeyNotfoundException
,因此在移除之前使用 ContainsKey()
方法检查现有键。
使用 Clear()
方法一次性移除所有元素。
示例:从 Hashtable 中移除元素
var cities = new Hashtable(){
{"UK", "London, Manchester, Birmingham"},
{"USA", "Chicago, New York, Washington"},
{"India", "Mumbai, New Delhi, Pune"}
};
cities.Remove("UK"); // removes UK
//cities.Remove("France"); //throws run-time exception: KeyNotFoundException
if(cities.ContainsKey("France")){ // check key before removing it
cities.Remove("France");
}
cities.Clear(); //removes all elements
Hashtable 类层次结构
下图说明了 Hashtable 类层次结构。

延伸阅读
- Hashtable 和 Dictionary 的区别
- Hashtable 属性和方法。