Serialization-implement iserializable

Source: Internet
Author: User
We can implement the iserializable interface to customize serialized behavior. This interface has only one method getobjectdata. This method is used to fill in the data required for serialization of class objects into the serializationinfo object. The formatter you use (such as binaryformatter) will construct the serializationinfo object and then call getobjectdata during serialization. Therefore, you need to implement getobjectdata to add the value you selected from the class and map it to the string name you selected. Note: If the class's parent class also implements iserializable, you should call the getobjectdata parent class implementation.
Example: Using System;
Using System. IO;
Using System. runtime. serialization;
Using System. runtime. serialization. formatters. Binary;
[Serializable]
Public   Class Insect: iserializable
{
Private   String Name;
Private   Int ID;
Public Insect ( String Name, Int ID)
{
This. Name=Name;
This. ID=ID;
}

Public   Override   String Tostring ()
{
ReturnString. Format ("{0 }:{ 1}", Name, ID );
}

Public Insect () {}

Public   Virtual   Void Getobjectdata (serializationinfo S, streamingcontext C)
{
S. addvalue (
"CommonName", Name );
S. addvalue (
"ID #", ID );
}

Private Insect (serializationinfo S, streamingcontext C)
{
Name
=S. getstring ("CommonName");
ID
=S. getint32 ("ID #");
}

}


Class Impiserialapp
{
Static   Void Main ( String [] ARGs)
{
Insect I
=   New Insect ( " Meadow Brown " , 12 );
Stream s
= File. Create ( " Insect. Bin " );
Binaryformatter B
=   New Binaryformatter ();
B. serialize (S, I );
S. Seek (
0 , Seekorigin. Begin );
Insect J
= (INSECT) B. deserialize (s );
S. Close ();
Console. writeline (j );
}

}

Insect. Bin contains the following information:
Diserializable, version = 0.0.0.0, culture = neutral, publickeytoken = NULL insect
CommonName ID # Meadow Brown

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.