c#中對object進行序列化和反序列化
阿新 • • 發佈:2019-01-09
有時候我們需要對一些資料進行二進位制序列化以達到儲存或傳輸的目的,這裡記錄一下對object的序列化和反序列化操作。
首先引入名稱空間:
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
object的序列化和反序列化測試:public static byte[] SerializeObject(object obj) { if (obj == null) return null; //記憶體例項 MemoryStream ms = new MemoryStream(); //建立序列化的例項 BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, obj);//序列化物件,寫入ms流中 byte[] bytes = ms.GetBuffer(); return bytes; } public static object DeserializeObject(byte[] bytes) { object obj = null; if (bytes == null) return obj; //利用傳來的byte[]建立一個記憶體流 MemoryStream ms = new MemoryStream(bytes); ms.Position = 0; BinaryFormatter formatter = new BinaryFormatter(); obj = formatter.Deserialize(ms);//把記憶體流反序列成物件 ms.Close(); return obj; }
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"]); }
結果:
注意:需要序列化的類一定要使用[Serializable]對其進行標記.