我创建了一个测试可序列化对象:
[Serializable]
public class TestObject : ISerializable
{
public string FirstName;
public TestObject()
{
}
public TestObject(SerializationInfo info, StreamingContext context)
{
FirstName = info.GetString("firstName");
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("firstName", FirstName);
}
}
然后序列化它:
var test = new TestObject { FirstName = "John" };
using (var stream = new FileStream(@"c:\temp\test.dat", FileMode.Create, FileAccess.Write))
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, test);
}
我更改了类,使其具有 OptionalFied 并尝试反序列化旧的序列化对象:
[Serializable]
public class TestObject : ISerializable
{
public string FirstName;
[OptionalField]
public string SecondName;
public TestObject()
{
}
public TestObject(SerializationInfo info, StreamingContext context)
{
FirstName = info.GetString("firstName");
SecondName = info.GetString("secondName");
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("firstName", FirstName);
}
当我更改构造函数以读取新的可选字段时,在“SecondName = info.GetString("secondName");”处抛出异常:
using (var stream = new FileStream(@"c:\temp\test1.dat", FileMode.Open, FileAccess.Read))
{
var formatter = new BinaryFormatter();
var myInstance = (TestObject)formatter.Deserialize(stream);
}
当您实现 ISerializable 时,是否真的不支持 OptionalFieldAttribute?