C# 二进制序列化和返序列化保存和读取对象信息
直接用明文文本的方式保存对象信息不是非常科学,现在用二进制序列化的方式来保存。
这里要先增加命名空间:using System.Runtime.Serialization.Formatters.Binary;
,还要给实体类增加序列化标识特性。
通过分层设计来实现:
实体类
Student.cs
:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SaveClassInfoToFile
{
[Serializable] // 增加序列化特性
class Student
{
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
public string Brithday { get; set; }
}
}
Service
StudentService.cs
:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace SaveClassInfoToFile
{
class StudentService
{
public Student stu;
// 序列化
public void SerializeObj()
{
// [1]创建文件流
FileStream fs = new FileStream(@"stuInfo.stu", FileMode.Create);
// [2]创建二进制格式
BinaryFormatter binaryFormatter = new BinaryFormatter();
// [3]调用序列化方法
binaryFormatter.Serialize(fs, stu);
// [4]关闭文件流
fs.Close();
}
// 返序列化
public Student DeserializeObj()
{
// 和序列化的步骤类似
FileStream fs = new FileStream(@"stuInfo.stu", FileMode.Open);
BinaryFormatter formatter = new BinaryFormatter();
Student student = formatter.Deserialize(fs) as Student;
fs.Close();
return student;
}
}
}
界面
Form.cs
:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SaveClassInfoToFile
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.StartPosition = FormStartPosition.CenterScreen;
}
// 序列化保存对象信息
private void button4_Click(object sender, EventArgs e)
{
Student stu = new Student() {
Name = this.txtName.Text.Trim(),
Age = int.Parse(this.txtAge.Text.Trim()),
Gender = this.txtGender.Text.Trim(),
Brithday = this.txtBrith.Text.Trim()
};
StudentService stuService = new StudentService() { stu = stu};
stuService.SerializeObj(); // 调用序列化方法
}
// 返序列化还原对象信息
private void button3_Click(object sender, EventArgs e)
{
StudentService studentService = new StudentService();
Student stu = studentService.DeserializeObj();
// 把数据读出来
this.txtAge.Text = stu.Age.ToString();
this.txtGender.Text = stu.Gender;
this.txtName.Text = stu.Name;
this.txtBrith.Text = stu.Brithday;
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了