BinaryFormatter序列化样例

mac2024-04-15  42

BinaryFormatter

BinaryFormatter详细介绍点击这里

以二进制格式序列化和反序列化对象或连接对象的整个图形。

以下样例实现了对象的序列化,反序列化,深拷贝

using System; using System.IO; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; namespace BinaryFormatterExample { class Program { static void Main(string[] args) { List<Student> students = new List<Student>() { new Student() {Id=1,Name="Tom",Age=5,Desc="desc" }, new Student() {Id=2,Name="Jack",Age=2,Desc="desc" }, new Student() {Id=3,Name="Harry",Age=10 ,Desc="desc"} }; //序列化 Save<List<Student>>(students, "students.bin"); //反序列化 List<Student> rStudents = Read<List<Student>>("students.bin"); //深拷贝 List<Student> copyStudents = DeepCopy<List<Student>>(rStudents); bool result = rStudents.Equals(copyStudents);//result=false } public static T DeepCopy<T>(T obj) { object desObj; using (MemoryStream ms = new MemoryStream()) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, obj); ms.Seek(0, SeekOrigin.Begin); desObj = bf.Deserialize(ms); } return (T)desObj; } public static void Save<T>(T obj, string path) { using (MemoryStream ms = new MemoryStream()) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, obj); ms.Seek(0, SeekOrigin.Begin); using (FileStream file = new FileStream(path, FileMode.Create, System.IO.FileAccess.Write)) { byte[] bytes = new byte[ms.Length]; ms.Read(bytes, 0, (int)ms.Length); file.Write(bytes, 0, bytes.Length); } } } public static T Read<T>(string path) { if (!File.Exists(path)) return default(T); object desObj; using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read)) { byte[] bytes = new byte[file.Length]; file.Read(bytes, 0, (int)file.Length); using (MemoryStream ms = new MemoryStream()) { ms.Write(bytes, 0, (int)file.Length); ms.Seek(0, SeekOrigin.Begin); BinaryFormatter bf = new BinaryFormatter(); desObj = bf.Deserialize(ms); } } return (T)desObj; } } [Serializable] class Student { private int id; private string name; private int age; [NonSerialized] private string desc; public int Id { get => id; set => id = value; } public string Name { get => name; set => name = value; } public int Age { get => age; set => age = value; } public string Desc { get => desc; set => desc = value; } } }

注意:要序列化的对象的类需要添加[Serializable],不需要序列化的字段用[NonSerialized]表明

最新回复(0)