C#使用BinaryFormatter进行序列化与反序列化

本文介绍了如何使用BinaryFormatter进行对象的序列化和反序列化操作。通过创建一个可序列化的Person类,实例化并设置属性,然后使用BinaryFormatter将对象序列化到文件中。同样,可以通过反序列化从文件中恢复对象状态。文章还提到了使用ISerializable接口自定义序列化行为的方法。
摘要由CSDN通过智能技术生成

BinaryFormatter

BinaryFormatter使用二进制格式化程序进行序列化。您只需创建一个要使用的流和格式化程序的实例,然后调用格式化程序的 Serialize 方法。流和要序列化的对象实例作为参数提供给此调用。类中的所有成员变量(甚至标记为 private 的变量)都将被序列化。

首先我们创建一个类:

[Serializable]
public class Person{
	public string name = "";
	public string email = "";
	public int age = 0;
}

Serializable属性用来明确表示该类可以被序列化。同样的,我们可以用NonSerializable属性用来明确表示类不能被序列化。

接着我们创建一个该类的实例,然后序列化,并存到文件里持久:

obj = new Person();
obj.name = "小明";
obj.email = "123456@qq.com" ;
obj.age = 20;

IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Create,
FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();

而将对象还原到它以前的状态也非常容易。首先,创建格式化程序和流以进行读取,然后让格式化程序对对象进行反序列化。

IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Open,
FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject) formatter.Deserialize(stream);
stream.Close();

Console.WriteLine("name: {0}", obj.name);
Console.WriteLine("email: {0}", obj.email);
Console.WriteLine("age: {0}", obj.age);

扩展(自定义实现序列化接口)

 class Person:ISerializable
    {
        public int age;
        public string name;
        public string sex;
        public Person() { }
        public Person(SerializationInfo info, StreamingContext context) {
            age=info.GetInt32("age");
            name=info.GetString("name");
        }

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("age", age);
            info.AddValue("name", name);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值