当使用Binary Formatter序列化对象时,应该注意以下几点:
被序列化的类必须标记为[Serializable],否则Binary Formatter将无法使用它。
Binary Formatter只能序列化不包含引用特性的正常类,不能序列化静态类、接口、抽象类等特殊类。
序列化的类必须拥有无参数的构造函数,因为反序列化的过程需要创建实例,而无参构造函数是在反序列化过程中创建对象的基础。
下面是一些示例代码,演示了如何使用Binary Formatter序列化和反序列化对象:
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class MyClass
{
public int myInt;
public string myString;
public MyClass()
{
myInt = 0;
myString = "";
}
}
public class Program
{
static void Main(string[] args)
{
MyClass myClass = new MyClass();
myClass.myInt = 42;
myClass.myString = "Hello World!";
// 序列化对象
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, myClass);
// 将序列化后的数据保存到文件中
using (FileStream file = new FileStream("data.bin", FileMode.Create, FileAccess.Write))
{
byte[] data = stream.ToArray();
file.Write(data, 0, data.Length);
}
// 从文件中读取序列化后的数据,并反序列化成对象
byte[] buffer;
using (FileStream file = new FileStream("data.bin", FileMode.Open, FileAccess.Read))
{
buffer = new byte[file.Length];
file.Read(buffer, 0, buffer.Length);
}
MemoryStream stream2 = new MemoryStream(buffer);
MyClass myDeserializedClass = formatter.Deserialize(stream2) as MyClass;
}
}