主要2种方式1.BinaryFormatter 2.XmlSerializer
创建对象
[Serializable] //如果要想保存某个class中的字段,必须在class前面加个这样attribute(C#里面用中括号括起来的标志符) public class Person { public int age; public string name; [NonSerialized] //如果某个字段不想被保存,则加个这样的标志 public string secret; }
1.BinaryFormatter (性能好)
class Program { static void Main(string[] args) { //序列化 Person person = new Person(); person.age = 18; person.name = "tom"; person.secret = "i will not tell you"; FileStream stream = new FileStream(@"c:\temp\person.dat", FileMode.Create);
BinaryFormatter bFormat = newBinaryFormatter(); bFormat.Serialize(stream, person); stream.Close(); //反序列化 Person person = new Person(); FileStream stream = new FileStream(@"c:\temp\person.dat", FileMode.Open);
BinaryFormatter bFormat = new BinaryFormatter(); person = (Person)bFormat.Deserialize(stream);//反序列化得到的是一个object对象.必须做下类型转换 stream.Close(); Console.WriteLine(person.age + person.name + person.secret);//结果为18tom.因为secret没有有被序列化. } }
2.XmlSerializer(常用)
//序列化 Person person = new Person(); person.age = 18; person.name = "tom"; person.secret = "i will not tell you"; FileStream stream = new FileStream(@"c:\temp\xmlFormat.xml", FileMode.Create); XmlSerializer xmlserilize = new XmlSerializer(typeof(Person)); xmlserilize.Serialize(stream, person); stream.Close(); //反序列化 Person person = new Person(); FileStream stream =new FileStrea (@"c:\temp\xmlFormat.xml",FileMode.Open); XmlSerializerxmlserilize = new XmlSerializer(typeof(Person)); person = (Person)xmlserilize.Deserialize(stream); stream.Close(); Console.WriteLine(person.age + person.name + person.secret);
总体思路:
序列化:
1.得到一个存储对象的类型
2.创建一个写入文件流
3.定义要序列化的类型
4.调用序列化方法
反序列化:
1.定义一个装载对象的类型
2.创建一个读出文件流
3.定义要反序列化的类型
4.调用反序列化方法