cowboy编译
chnenzizhao@hotmail.com
2004.4.21
介绍
本文介绍了,在.net里,使用哈希表和串行化的C#用法。这里使用的示例应用程序是
哈系表是“键-值”对的集合。在.net里,类Hashtable是哈希表的实现。通
private Hashtable table = new Hashtable();
public void AddEntry(BookEntry entry)
{
table.Add( entry.GetPerson(), entry );
}
哈系表建好后,你就可以通过调用Hashtable类的索引来检索这些成员。
public BookEntry GetEntry(Person key)
{
return (BookEntry) table[key];
}
可以通过调用Remove方法来移出条目。这里,使用键来区分要移出的条目。
public void DeleteEntry(Person key)
{
table.Remove( key );
}
通过串行化,我们可以把这个哈系表保存到文件中。串行化就是把对象转换成线性的字节序
public void Save()
{
Stream s = File.Open("Phone.bin", FileMode.Create, FileAccess.ReadWrite);
BinaryFormatter b = new BinaryFormatter();
b.Serialize(s, table);
s.Close();
}
如下面所演示的那样,哈系表对象可以通过调用Deserialize 方法转换回来。
s = File.Open("Phone.bin", FileMode.Open, FileAccess.Read);
BinaryFormatter b = new BinaryFormatter();
table = (Hashtable) b.Deserialize(s);
我希望这个简短的对.net里面哈系表对象和序列化的简单介绍会对你有用。