1 The following is a serialized class that I wrote
public static Class Objserialize
{
<summary>
Serializes an object array of obj, data serialization of buffers in memory
</summary>
<param name= "obj" ></param>
<returns></returns>
public static byte[] Serialize (Object obj)
{
byte[] arr = null;
if (obj!=null)
{
The MemoryStream class is used to read and write data to memory instead of disk
using (MemoryStream ms=new MemoryStream ())
{
Serialization to write something in memory to the hard disk
BinaryFormatter Fomatter = new BinaryFormatter ();
Fomatter. Serialize (MS, obj);
Ms. Flush ();
arr = Ms. ToArray ();
}
}
return arr;
}
public static object Deserialize (byte[] arr)
{
Object obj = null;
using (MemoryStream ms=new MemoryStream ())
{
Ms. Write (arr, 0, arr.) Length);
Ms. Flush ();
Ms. Position = 0;
BinaryFormatter formatter = new BinaryFormatter ();
Obj= Formatter. Deserialize (MS);
}
return obj;
}
}
2 Testing This class
I created myself a student object with only the ID and name two attributes
Console test code here you go. The Student class is marked as Serializable
Student stu = new Student ()
{
ID = 1,
Name = "Wangbaoqiang"
};
Byte[] arr= objserialize.serialize (STU);
for (int i = 0; i < arr. Length; i++)
{
Console.WriteLine (Arr[i]);
}
The results are as follows:
The deserialized test code and results are as follows
Student ss= (Student) objserialize.deserialize (arr);
Console.WriteLine ("{0}----{1}", Ss.id,ss. Name);
How C # uses MemoryStream and BinaryFormatter for serialization and serialization of objects