对象序列化与反序列化
对于要进行序列化操作的对象需要添加[Serializable]声明,例如:
namespace filetest { [Serializable] //必须添加序列化特性 class User { public String name; public int age; } }
进行序列化操作时需要导入以下两个命名空间:
using System.Runtime.Serialization.Formatters.Binary; using System.IO;
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Serialization.Formatters.Binary; using System.IO; namespace filetest { class Program { static void Main(string[] args) { string file = @"E:\vs_workspace\file_test\obj.bat"; ObjDeserialize(file); } static void ObjSerialize(string file) { User user = new User(); user.name = "zhangsan"; user.age = 25; using (Stream output = File.Create(file)) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(output, user); } } static void ObjDeserialize(string file) { using (Stream input = File.OpenRead(file)) { BinaryFormatter bf = new BinaryFormatter(); User user = (User)bf.Deserialize(input); Console.WriteLine("User.name:{0}\nUser.age:{1}", user.name,user.age); } } } }