Binaryformatter serialization instance (2)

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.