标签:des style class blog code color
小鸟成长笔记;
持久化:将对象的状态保存起来;
序列化:将对象的状态持久化到存储设备中(磁盘);
注意:1.要将类标记为[Serializable]才可以被序列化
2.以二进制的方式序列化,而不是文本文档
[Serializable] class Person { public string Name { get; set; } public int Age{ get; set; } }
序列化
static void Main(string[] args) { Person p = new Person(); p.Name="HaoLiu"; p.Age=19; using(FileStream fs=new FileStream("se.bin",FileMode.Create)){ System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bf.Serialize(fs, p); } }
反序列化
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf=new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); using(FileStream fs=new FileStream("se.bin",FileMode.Open)){ object obj = bf.Deserialize(fs); Person p = obj as Person;//强制转换为Person对象 Console.WriteLine(p.Name+":"+p.Age); Console.ReadKey(); }
标签:des style class blog code color
原文地址:http://www.cnblogs.com/liuhao2050/p/3804875.html