The comments are very detailed and can be easily understood at a glance.
Code
Using System;
Namespace Serdser
{
[Serializable] // This class can be serialized.
Public Class Course
{
Public String Name;
Public String Description;
/// <Summary>
/// You must have a constructor without parameters.
/// </Summary>
Public Course ()
{}
Public Course ( String Name, String Description)
{
Name = Name;
Description = Description;
}
}
}
Code
Using System;
Namespace Serdser
{
[Serializable] // This class can be serialized and deserialized if it can be serialized.
Public Class Person
{
Private String Name;
Public String Name
{
Get { Return Name ;}
Set {Name = Value ;}
}
Public String Sex;
Public Int Age = 31 ;
Public Course [] courses;
Public Person (){} // No parameter Constructor
Public Person ( String Name)
{
This . Name = Name;
Sex = " Male " ;
}
}
}
Code
Using System;
Using System. IO; // File Operations
Using System. xml. serialization; // Introduce the namespace used for serialization
Namespace Serdser
{
Public Class Program
{
Static Void Main ( String [] ARGs)
{
Program P = New Program ();
P. serialize ();
P. deserialize ();
}
Public Void Serialize () // Serialize person class
{
Console. writeline ( " Start serialization " );
Person C = New Person ( " Lhking " );
C. Courses = New Course [ 2 ];
C. Courses [ 0 ] = New Course ( " English " , " Communication Tools " );
C. Courses [ 1 ] = New Course ( " Mathematics " , " Natural Sciences " );
Xmlserializer XS = New Xmlserializer ( Typeof (Person ));
Stream stream = New Filestream ( " C: \ sedes. xml " , Filemode. Create, fileaccess. Write, fileshare. readwrite );
Xs. serialize (stream, C );
Stream. Close ();
Stream stream1 = New Filestream ( " C: \ sedes.txt " , Filemode. Create, fileaccess. Write, fileshare. None );
Xs. serialize (stream1, C );
Stream1.close ();
// The content of the two files is the same.
Console. writeline ();
Console. writeline ( " Serialized " );
System. Diagnostics. process. Start ( @" C: \ sedes. xml " );
}
Public Void Deserialize () // Deserializing the person class
{
Console. writeline ( " Start deserialization " );
Console. writeline ( " Deserialization is completed, output .. " );
System. Threading. thread. Sleep ( 2000 ); // Thread tentative 2 seconds
Xmlserializer XS = New Xmlserializer ( Typeof (Person ));
Stream stream = New Filestream ( " C: \ sedes. xml " , Filemode. Open, fileaccess. Read, fileshare. readwrite );
Person P = (Person) XS. deserialize (Stream );
Console. writeline (P. Name );
Console. writeline (P. Age );
Console. writeline (P. Courses. Length );
Console. writeline (P. Courses [ 0 ]. Name );
Console. writeline (P. Courses [ 0 ]. Description );
Console. writeline (P. Courses [ 1 ]. Name );
Console. writeline (P. Courses [ 1 ]. Description );
Console. Read ();
}
}
}
SourceProgramDownload:/files/lhking/serdser.rar