.NET Core 對象到字節數組的序列化和反序列化
阿新 • • 發佈:2019-01-19
objects urn image 序列 mes key ons space 出了
.NET Core中利用MemoryStream和BinaryFormatter可以實現對象到字節數組的序列化和反序列化:
定義ObjectSerializer類,實現對象到字節數組的序列化和反序列化
using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace Assembly { public static class ObjectSerializer { /// <summary>/// 將一個object對象序列化,返回一個byte[] /// </summary> /// <param name="obj">能序列化的對象</param> /// <returns></returns> public static byte[] ObjectToBytes(object obj) { using (MemoryStream ms = new MemoryStream()) { IFormatter formatter= new BinaryFormatter(); formatter.Serialize(ms, obj); return ms.GetBuffer(); } } /// <summary> /// 將一個序列化後的byte[]數組還原 /// </summary> /// <param name="Bytes"></param> /// <returns></returns>public static object BytesToObject(byte[] Bytes) { using (MemoryStream ms = new MemoryStream(Bytes)) { IFormatter formatter = new BinaryFormatter(); return formatter.Deserialize(ms); } } } }
用BinaryFormatter做序列化和反序列化最大的一個問題是,序列化和反序列化的類型必須是標記為[Serializable]的,也就是SerializableAttribute特性,而且SerializableAttribute特性是無法被繼承的,例如我們如果有個類People標記了[Serializable],如下所示:
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApp2 { [Serializable] public class People { public string Name { get; set; } public int Age { get; set; } } }
由於People類標記了[Serializable],所以它可以被BinaryFormatter序列化和反序列化,但是假如現在還有個類Child繼承People,Child類沒有被標記為[Serializable],那麽Child類是無法被BinaryFormatter序列化和反序列化的,因為如上所述SerializableAttribute特性是無法被繼承的。Child類如下所示:
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApp2 { public class Child : People { } }
建立.NET Core控制臺項目,在Main方法中運行如下代碼:
class Program { static void Main(string[] args) { var people = new People() { Name = "王大錘", Age = 30 }; var data = ObjectSerializer.ObjectToBytes(people); people = ObjectSerializer.BytesToObject(data) as People; Console.WriteLine("Press any key to end..."); Console.ReadKey(); } }
可以看到People類可以被成功序列化和反序列化
將Main方法的代碼改為如下,再運行:
class Program { static void Main(string[] args) { var child = new Child() { Name = "王大錘", Age = 30 }; var data = ObjectSerializer.ObjectToBytes(child); child = ObjectSerializer.BytesToObject(data) as Child; Console.WriteLine("Press any key to end..."); Console.ReadKey(); } }
可以看到代碼在ObjectSerializer類的ObjectToBytes方法中拋出了異常,異常提示Child類沒有被標記位[Serializable]
.NET Core 對象到字節數組的序列化和反序列化