What is serialization?
---. Net's run-time environment is used to support the mechanism of user-defined type fluidization. It is the process of storing the state of an object instance to storage media. In this procedure, the public and private fields of the object, as well as the name of the class, including the assembly in which the class resides, are converted to a byte stream, which is then written to the data flow. When the object is deserialized later, the exact same copy of the original object is created.
Purpose of Serialization:
1, in some form of storage to make the custom object persistent;
2. Transfer objects from one place to another.
Essentially, the serialization mechanism converts the value of a class to a generic (that is, continuous) byte stream, which can then be written to a disk file or to any other streaming target. To actually write this flow, you use the serialize and deserialize methods in the classes that implement the IFormatter interface.
These two classes are available in the. NET Framework:
First, BinaryFormatter
BinaryFormatter is serialized using a binary formatter. You simply create an instance of the stream and formatter to use, and then invoke the Serialize method of the formatter. The stream and the object instance to serialize are supplied as arguments to this call. All member variables (even variables marked private) in a class are serialized.
First we create a class:
[Serializable]
public class MyObject {
public int n1 = 0;
public int n2 = 0;
public String str = NULL;
}
The Serializable property is used to explicitly indicate that the class can be serialized. Similarly, we can use the Nonserializable attribute to explicitly indicate that a class cannot be serialized.
We then create an instance of the class, and then serialize it to the file for persistence:
MyObject obj = new MyObject ();
OBJ.N1 = 1;
Obj.n2 = 24;
Obj.str = "some strings";
IFormatter formatter = new BinaryFormatter ();
Stream stream = new FileStream ("Myfile.bin", FileMode.Create,
FileAccess.Write, Fileshare.none);
Formatter. Serialize (stream, obj);
Stream. Close ();
It is also very easy to restore an object to its previous state. First, you create the formatter and stream for reading, and then let the formatter deserialize the object.
IFormatter formatter = new BinaryFormatter ();
Stream stream = new FileStream ("Myfile.bin", FileMode.Open,
FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject) formatter. Deserialize (FromStream);
Stream. Close ();
//Below is proof
Console.WriteLine ("N1: {0}", obj.n1);
Console.WriteLine ("N2: {0}", obj.n2);
Console.WriteLine ("str: {0}", OBJ.STR);