序列化步骤
反序列化步骤
序列化:将对象转换为二进制。
反序列号:将二进制转换为对象。
作用:传输数据
序列化:
1、将这个类标记为可以被序列化的。
[Serializable]//表示类可以被序列化
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
namespace _088_序列化和反序列化
{
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\46124\Desktop\CSharpTestFour.txt", FileMode.OpenOrCreate, FileAccess.Write))
{
//开始序列化对象 通过BinaryFormatter类中的Serialize方法实现
BinaryFormatter bf1 = new BinaryFormatter();
bf1.Serialize(fsWrite, p);
Console.WriteLine("序列化成功");
}
string s = File.ReadAllText(@"C:\Users\46124\Desktop\CSharpTestFour.txt", Encoding.Default);
Console.WriteLine(s);
//接受二进制,反序列化成对象
Person person;
using (FileStream fsRead = new FileStream(@"C:\Users\46124\Desktop\CSharpTestFive.txt", FileMode.OpenOrCreate, FileAccess.Read))
{
//开始反序列化对象 通过BinaryFormatter类中的Deserialize方法实现
BinaryFormatter bf2 = new BinaryFormatter();
person = (Person)bf2.Deserialize(fsRead);
}
person.SayHello();
Console.ReadKey();
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace _088_序列化和反序列化
{
[Serializable]//表示类可以被序列化
class Person
{
private string _name;
public string Name { get => _name; set => _name = value; }
private char _gender;
public char Gender { get => _gender; set => _gender = value; }
private int _age;
public int Age { get => _age; set => _age = value; }
public void SayHello()
{
Console.WriteLine("我的名字是{0},性别{1},今年{2}岁了", this.Name, this.Gender, this.Age);
}
}
}