C# 把类实例保存到文件里(类的序列化和反序列化)

在类的上面加上[Serializable]属性就可以了,表示这个类是可以序列化的

[Serializable]
public class People
{
    public string Name { get; set; }
    public int Age { get; set; }
}

然后采用如下代码将类的实例序列化到文件中

//序列化
FileStream fs = new FileStream(@"D:\Program\CSharp\NGramTest\NGramTest\serializePeople.dat", FileMode.Create);
People p = new People() { Name = "Haocheng Wu", Age = 24 };

BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, p);
fs.Close();

这样就能够上面的那个文件就保存了这个类的实例,如果想要读出来,就可以用

//反序列化
fs = new FileStream(@"D:\Program\CSharp\NGramTest\NGramTest\serializePeople.dat", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
People p = bf.Deserialize(fs) as People;

运用同样的方法,也可以把一个类的List完全序列化到文件中

//序列化List
FileStream fs = new FileStream(@"D:\Program\CSharp\NGramTest\NGramTest\serializePeople.dat", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();

List<People> ps = new List<People>();
ps.Add(new People() { Name = "Haocheng Wu", Age = 24 });
ps.Add(new People() { Name = "James Wu", Age = 23 });

bf.Serialize(fs, ps);
fs.Close();

读出来的方法也是一样的:

//反序列化List
fs = new FileStream(@"D:\Program\CSharp\NGramTest\NGramTest\serializePeople.dat", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
List<People> ps = bf.Deserialize(fs) as List<People>;
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值