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