序列化和反序列化
序列化和反序列化
对象--->二进制
二进制--->对象
目的:
--->传输数据
--->保存对象的状态
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace _05序列化和反序列化 { class Program { static void Main(string[] args) { //要将p这个对象 传输给对方电脑 //Person p = new Person(); //p.Name = "张三"; //p.Age = 19; //p.Gender = '男';
//负责写入的流 //using (FileStream fsWrite = new FileStream(@"C:\Users\SpringRain\Desktop\111.txt", FileMode.OpenOrCreate, FileAccess.Write)) //{ // //开始序列化对象,将对象序列化为二进制 // BinaryFormatter bf = new BinaryFormatter(); // bf.Serialize(fsWrite, p); //} //Console.WriteLine("序列化成功"); //Console.ReadKey(); //接收对方发送过来的二进制 反序列化成对象 Person p; using (FileStream fsRead = new FileStream(@"C:\Users\SpringRain\Desktop\111.txt", FileMode.OpenOrCreate, FileAccess.Read)) { BinaryFormatter bf = new BinaryFormatter(); p = (Person)bf.Deserialize(fsRead); } Console.WriteLine(p.Name); Console.WriteLine(p.Age); Console.WriteLine(p.Gender); Console.ReadKey(); } } [Serializable] public class Person { private string _name; public string Name { get { return _name; } set { _name = value; } } private char _gender; public char Gender { get { return _gender; } set { _gender = value; } } private int _age; public int Age { get { return _age; } set { _age = value; } } } }
保存对象的状态案例
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; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace _16序列化和反序列化 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { //保存当前应用程序的状态 MovieConfig mc = new MovieConfig(); mc.Height = 512; mc.Width = 800; mc.JinDu = 88; mc.Volumn = 70; //标记这个类可以被序列化 using (FileStream fsWrite = new FileStream("config.config", FileMode.OpenOrCreate, FileAccess.Write)) { //创建序列化对象 BinaryFormatter bf = new BinaryFormatter(); //开始序列化 bf.Serialize(fsWrite, mc); } // MessageBox.Show("当前应用程序状态保持成功!!!"); } private void Form1_Load(object sender, EventArgs e) { if (File.Exists("config.config")) { MovieConfig mc; //反序列化 using (FileStream fsRead = new FileStream("config.config", FileMode.OpenOrCreate, FileAccess.Read)) { BinaryFormatter bf = new BinaryFormatter(); mc = bf.Deserialize(fsRead) as MovieConfig; } this.Height = mc.Height; this.Width = mc.Width; this.progressBar1.Value = mc.JinDu; textBox1.Text = "当前音量" + mc.Volumn; } } } }