程序序列化操作

来源:互联网 发布:mac qq游戏大厅 编辑:程序博客网 时间:2024/06/05 04:37

 序列化的操作:
 1:导入命名空间:using System.Runtime.Serialization.Formatters.Binary;
 2:要给类加标记,标记可以被序列化,要序列化对象的类与父类  [Serializable]
 3:准备一个流:FileStream fileStream = new FileStream(@"D:\", FileMode.Create, FileAccess.Write);
 4:准备序列化的工具:BinaryFormatter bft = new BinaryFormatter();
 5:进行序列化:
 using (fileStream)
{
    bft.Serialize(fileStream, list);
}
进行反序列化操作:
1:准备一个流:FileStream file = new FileStream(@"D:\txt.dat", FileMode.Open, FileAccess.Read);
2:准备一个反序列化的工具:BinaryFormatter bft = new BinaryFormatter();
3:开始反序列化:
using (file)
{
    s = (List < Student >) binaryFormatter.Deserialize(file);
}
序列化的一个应用:
namespace 序列化的应用
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void SaveMge()//注意这个方法要放到程序初始化的开始,这样就吧程序上次关闭的记录保存下来了
        {
            MyClass myClass = new MyClass();
            myClass.x = this.Location;
            myClass.y = this.Size;
            using (FileStream file = new FileStream(@"D:\data.dat", FileMode.Create, FileAccess.Write))
            {
                BinaryFormatter bin = new BinaryFormatter();
                bin.Serialize(file, myClass);
            }
        }
        private void OpenMge()
        {
           
            if (File.Exists(@"D:\data.dat"))
            {
                FileStream file = new FileStream(@"D:\data.data", FileMode.Open, FileAccess.Read);
                BinaryFormatter bin = new BinaryFormatter();
               
                 MyClass myClass = (MyClass)bin.Deserialize(file);
                 this.StartPosition = FormStartPosition.Manual;

                this.Location = myClass.x;
                this.Size = myClass.y;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            OpenMge();
        }
    }
}