Serialization: Also known as Serializable, is the mechanism used by the. NET runtime environment to support the flow of user-defined types. The purpose is to persist the custom object in some form of storage, or to transfer the object from one place to another.
Generally there are three ways: 1, is to use BinaryFormatter serialization of binary, 2, using XmlSerializer serialization of XML, 3, using the SOAP protocol for serialization. Here we summarize the binary serialization first.
namespaces: System.Runtime.Serialization.Formatters.Binary;
System.IO;
1). First build a serializable class
[Serializable]
Class Person
{
private string name;
public string Name
{get {return name;}
set {name = value;}
}
[NonSerialized]//age This field is not serialized
private int age;
public int Age
{
get {return age;}
set {age = value;}
}
Public person () {}
Public person (string name, int age) {
THIS.name = name;
This.age = age;
}
public void Say () {
Console.WriteLine ("Hello,my name is{0}, I am {1}years old.", Name,age);
} }
In the main function:
list<person> persons = new list<person> ();//or Person p=new person ("Chen", 24);
person P1 = new Person ("Chen", 24);
person P2 = new person ("Li", 23);
Persons. Add (p1);
Persons. ADD (p2);
Xuliehua (persons); Call the static serialization method
Fanxuliehua (); Call the static deserialization method
public static void Xuliehua (list<person> persons)//serialization method
{
FileStream fs = new FileStream ("Person.bin", filemode.create);//create a file stream to write to the file
BinaryFormatter bf = new BinaryFormatter ();//using the CLR binary formatter
Bf. Serialize (fs,persons); Serializing to Hard disk
Fs. Close ();//Closed file stream
}
public static void Fanxuliehua ()//deserialization method
{
FileStream fs = new FileStream ("Person.bin", FileMode.Open);//Open stream file
binaryformatter bf = New BinaryFormatter ();
list<person> persons = bf. Deserialize (FS) as list<person>;//deserializes from the hard disk;
// or person p= (person) bf. Deserialize (FS); Corresponds to the above or
Fs. Close ();//Closed file stream
for (int i = 0; i < persons. count;i++)
{
Persons[i].say ();
}
}
Result: Hello,my name is Chen, I am 0years.
Hello,my name is Li, I am 0years old.//name serialized, and age is not serialized, so it is 0.
Note: When inheriting, both the parent and child classes need to be serialized.
C # serialization Binary