net里的哈希表和串行化
cowboy编译
chnenzizhao@hotmail.com
2004.4.21
介绍
本文介绍了,在.net里,使用哈希表和串行化的c#用法。这里使用的示例应用程序是一个电话簿。电话簿应用程序,是一个控制台的程序。它允许你添加,查看,列出和删除它里面的姓名和电话号码。
哈系表是“键-值”对的集合。在.net里,类hashtable是哈希表的实现。通过调用add方法,传递你想添加的键值对,可以完成添加。作为键来使用的这些对象,必须实现object.equals 和object.gethashcode方法。
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 );
}
通过串行化,我们可以把这个哈系表保存到文件中。串行化就是把对象转换成线性的字节序列,以便存储到存储设备中或者传送到其他地方,的过程。这个任务,可以由binaryformater 类来完成。它把哈系表对象串行化为一个文件流。
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里面哈系表对象和序列化的简单介绍会对你有用。
