Serialization and deserialization of object in C # __c#

Source: Internet
Author: User

Sometimes we need to binary serialize some data for the purpose of saving or transmitting, and here we will record the serialization and deserialization operation of object.


First introduce namespaces:

Using System.IO;
Using System.Runtime.Serialization.Formatters.Binary;
Serialization and deserialization of object
	public static byte[] SerializeObject (object obj)
	{
		if (obj = = null) return
			null;
		Memory instance
		MemoryStream ms = new MemoryStream ();
		Creates an instance of serialization
		BinaryFormatter formatter = new BinaryFormatter ();
		Formatter. Serialize (MS, OBJ);//serialized object, written in Ms Stream  
		byte[] bytes = Ms. GetBuffer ();
		return bytes;
	}
	public static Object Deserializeobject (byte[] bytes)
	{
		object obj = null;
		if (bytes = null) return
			obj;
		Use the byte[] to create a memory stream
		MemoryStream ms = new MemoryStream (bytes);
		Ms. Position = 0;
		BinaryFormatter formatter = new BinaryFormatter ();
		obj = formatter. Deserialize (MS);//reverse the memory stream into object  
		Ms. Close ();
		return obj;
	}
Test:

    public static void Serializedictest () {
        
        dictionary<string, int> test = new dictionary<string, int> ();
        
        Test. ADD ("1", 1);
        Test. ADD ("2", 2);
        Test. ADD ("3", 4);
        
        byte[] Testbyte = tools.serializeobject (test);
        
        dictionary<string, int> testdic = (dictionary<string, int>) tools.deserializeobject (testbyte);
        
        Debug.Log ("[Serializedictest]  :" + testdic["3"]);
    }

Results:


Note: The classes that need to be serialized must be marked with [Serializable].




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.