C#序列化和反序列化

好处:可以直接保存对象,文件保存对象

1.首先到要保存的类加上序列化标记:[Serializable]

[Serializable]  //对象可序列化标记
    internal class Student
    {
        public string Name { get; set; }

        public int Age { get; set; }
    }

2.使用的时候序列化

FileStream fs = new FileStream(路径+文件名, FileMode.Create)

BinaryFormatter format = new BinaryFormatter();

format.Seriablize(fs, student);        //第二个参数是对象实例,将对象保存到了文件中

//封装数据
            Student student = new Student()
            {
                Name = this.tb_Name.Text.Trim(),
                Age = Convert.ToInt16(this.tb_Age.Text.Trim())
            };

            //【1】创建文件流
            FileStream fs = new FileStream("D:\\desktop\\tmp\\objstudent.txt", FileMode.Create);
            //【2】创建二进制格式化器
            BinaryFormatter formatter = new BinaryFormatter();
            //调用序列化方法
            formatter.Serialize(fs, student);
            fs.Close();

3.反序列化

FileStream fs = new FileStream(路径+文件名, FileMode.Open)

BinaryFormatter format = new BinaryFormatter();

Student student = (Student)format.Deseriablize(fs);        //返回的是object类型

//创建文件流
            FileStream fs = new FileStream("D:\\desktop\\tmp\\objstudent.txt", FileMode.Open);
            BinaryFormatter formatter = new BinaryFormatter();
            Student student = (Student)formatter.Deserialize(fs);

你可能感兴趣的:(C#特性,c#,开发语言,windows)