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].