c#序列化和反序列化
序列化:将对象转为二进制
反序列化:将二进制转为对象
目的:传输文件
序列化步骤:
1.将类标记为可序列化
2.用binaryformatter类序列化类,写入
反序列化步骤:
1. 读取文件
2.用binaryformatter类反序列化类
using System.Runtime.Serialization.Formatters.Binary; //引用
namespace test
{
class Program
{
static void Main(string[] args)
{
Dunk d = new Dunk();
d.A = 7;
//将对象d通过文件传给对方
string Path = "D:\\1.txt";
using (FileStream fs = new FileStream(Path, FileMode.OpenOrCreate, FileAccess.Write))
{
//new一个序列化对象,用其方法序列化
BinaryFormatter bf = new BinaryFormatter();
//将流和序列化对象传入,自动写
bf.Serialize(fs, d);
}
//通过文件将对象反序列化
Dunk d2;
using (FileStream fs2 = new FileStream(Path, FileMode.OpenOrCreate, FileAccess.Read))
{
BinaryFormatter bf2 = new BinaryFormatter();
// deserialize返回object父类类型,需先声明一个,大转小-显式转换
d2 = (Dunk)bf2.Deserialize(fs2);
}
Console.WriteLine(d2.A);
Console.ReadKey();
}
}
//必须声明可以序列化
[Serializable]
public class Dunk
{
private int _a;
public int A { get => _a; set => _a = value; }
}
}

浙公网安备 33010602011771号