C#序列化和反序列化

序列化和反序列化概述

序列化就是将对象实例的状态存储到存储媒体的过程

  1. 标记类为可序列化

    1
    2
    3
    4
    5
    [Serializable]
    class Student
    {
    //
    }
  2. 将实例化的对象序列化

    1
    2
    3
    4
    5
    6
    7
    public void Save(Student stu)
    {
    FileStream fs=new FileStream(stu.name+".txt",FileMode.Creat,FileAccess.Write);
    BinaryFormatter bf=new BinaryFormatter();
    bf.Serialize(fs,stu);//序列化
    fs.close();
    }
  3. 反序列化

    1
    2
    3
    4
    5
    6
    7
    8
    public void Load(String path)
    {
    Student stu=new Student();
    FileStream fs=new FileStream(path,FileMode.Open,FileAccess.Read);
    BinaryFormatter bf=new BinaryFormatter();
    stu=bf.Deserialize(fs) as Student;//反序列化
    fs.Close();
    }
悠哉码农的日常 wechat
扫一扫上面的微信公众号
坚持原创技术分享,谢谢你为我充电