接下来,实现Voucher类的反序列化,代码如下:
public Voucher Deserialize(string filename)
{
BinaryFormatter formatter = new BinaryFormatter();
Voucher voucher = null;
FileStream fs = new FileStream(filename, FileMode.Open);
try
{
voucher = (Voucher)formatter.Deserialize(fs);
}
finally
{
fs.Close();
}
return voucher;
}
{
BinaryFormatter formatter = new BinaryFormatter();
Voucher voucher = null;
FileStream fs = new FileStream(filename, FileMode.Open);
try
{
voucher = (Voucher)formatter.Deserialize(fs);
}
finally
{
fs.Close();
}
return voucher;
}
创建FileStream的代码没有放到try块中,因为如果文件不存在,new FileStream会抛出异常,并不会造成资源的丢失。此后的formatter.Deserialize也没有处理异常,这是因为Deserialize本身无法确定发生导常时该如何处理,它只要保证需要释放的资源都被释放。在实际的Library开发中,try...finally的应用比try...catch要多得多。
同样,添加NUnit的测试方法:
[Test]
public void TestDeserializeVoucher()
{
VoucherSerializer serializer = new VoucherSerializer();
Voucher voucher = serializer.Deserialize("voucher.dat");
Assert.AreEqual(voucher.VoucherId, "2005012900001");
Assert.AreEqual(voucher.Creator, "xingd");
}
public void TestDeserializeVoucher()
{
VoucherSerializer serializer = new VoucherSerializer();
Voucher voucher = serializer.Deserialize("voucher.dat");
Assert.AreEqual(voucher.VoucherId, "2005012900001");
Assert.AreEqual(voucher.Creator, "xingd");
}
运行NUnit GUI,测试通过。