How C # uses MemoryStream and BinaryFormatter for serialization and serialization of objects

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.