Next, implement voucher class deserialization,CodeAs follows:
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;
}
The code for creating a filestream is not put in the try block, because if the file does not exist, new filestream throws an exception and does not cause resource loss. The subsequent formatter. deserialize does not handle any exceptions. This is because Deserialize itself cannot determine how to deal with the issue of normal export, as long as it ensures that all resources to be released are released. In actual library development, try... finally has more applications than try... catch.
Similarly, add the nunit Test method:
[Test]
Public Void Testdeserializevoucher ()
{
Voucherserializer serializer = New Voucherserializer ();
Voucher voucher = Serializer. deserialize ( " Voucher. dat " );
Assert. areequal (voucher. voucherid, " 2005012900001 " );
Assert. areequal (voucher. creator, " Xingd " );
}
Run nunit GUI and the test passes.