19.2.2 Hashtable
Hashtable实现了IDictionary、ICollection以及IEnumerable接口,如图19-7所示。
Hashtable表示键(key)/值(value)对的集合,这些键/值对根据键的哈希代码进行组织。每一对键/值对保存在一个DictionaryEntry中,因此一个Hashtable集合实际上也是DictionaryEntry实例对象的集合,如图19-8所示。
图 19-7 Hashtable类图
图 19-8 Hashtable示意图
关于Hashtable需要注意的是:
❑BCL仅提供了Hashtable的非泛型版本;
❑Hashtable类中的键不允许重复,但值可以;
❑Hashtable类所存储的键/值对中,值可以为null,但键不能为null;
❑Hashtable类不支持排序操作。
代码清单19-2 演示了Hashtable的一般使用方法。
代码清单19-2 Hashtable示例
using System;
using System.Collections;
namespace ProgrammingCSharp4
{
class CollectionSample
{
public static void Main()
{
Hashtable openWith=new Hashtable();
//向集合中添加数据,注意key不能重复,但value可以
openWith.Add("txt","notepad.exe");
openWith.Add("bmp","paint.exe");
openWith.Add("dib","paint.exe");
openWith.Add("rtf","wordpad.exe");
//如果key冲突了会抛出运行时异常,这种问题只能在运行时才能暴露
try
{
openWith.Add("txt","winword.exe");
}
catch
{
Console.WriteLine("An element with Key=\"txt\"already exists.");
}
//通过key获取它所对应的value
Console.WriteLine("For key=\"rtf\",value={0}.",openWith["rtf"]);
//通过key来修改原来的值
openWith["rtf"]="winword.exe";
Console.WriteLine("For key=\"rtf\",value={0}.",openWith["rtf"]);
//如果key不存在,则自动添加,并将新的key/value保存到集合中
openWith["doc"]="winword.exe";
//使用ContainsKey可以判断指定的key是否存在
if(!openWith.ContainsKey("ht"))
{
openWith.Add("ht","hypertrm.exe");
Console.WriteLine("Value added for key=\"ht\":{0}",openWith["ht"]);
}
//当使用枚举器来访问一个Hashtable集合时,我们得到的是DictionaryEntry类型,它保存了key和value
Console.WriteLine();
foreach(DictionaryEntry de in openWith)
{
Console.WriteLine("Key={0},Value={1}",de.Key,de.Value);
}
//通过Values属性可以获取值的集合
ICollection valueColl=openWith.Values;
//通过Values属性返回的集合是强类型的,使用元素的实际类型来访问它们
Console.WriteLine();
foreach(string s in valueColl)
{
Console.WriteLine("Value={0}",s);
}
//通过Keys属性获取所有key的集合
ICollection keyColl=openWith.Keys;
//通过Keys属性获取到key集合也是强类型的
Console.WriteLine();
foreach(string s in keyColl)
{
Console.WriteLine("Key={0}",s);
}
//使用Remove移除一个key/value对
Console.WriteLine("\nRemove(\"doc\")");
openWith.Remove("doc");
if(!openWith.ContainsKey("doc"))
{
Console.WriteLine("Key\"doc\"is not found.");
}
}
}
}
上述代码的运行结果为:
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=rtf,Value=winword.exe
Key=bmp,Value=paint.exe
Key=ht,Value=hypertrm.exe
Key=dib,Value=paint.exe
Key=doc,Value=winword.exe
Key=txt,Value=notepad.exe
Value=winword.exe
Value=paint.exe
Value=hypertrm.exe
Value=paint.exe
Value=winword.exe
Value=notepad.exe
Key=rtf
Key=bmp
Key=ht
Key=dib
Key=doc
Key=txt
Remove("doc")
Key"doc"is not found.
请按任意键继续……