c# - BinaryFormatter OptionalField with ISerializable -
i create test serializable object:
[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); } }
and serialize it:
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); }
i change class has optionalfied , try deserialize old serialized object:
[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); }
when change constructor read new optional field, exception thrown @ "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); }
is case optionalfieldattribute not supported when implement iserializable?
for old serialzed object there not secondname field, serializationentry wouldn't exist.
you need check if entry exists before access value:
foreach (serializationentry entry in info) { switch (entry.name) { case "firstname": firstname = (string)entry.value; break; case "secondname": secondname = (string)entry.value; break; } }
Comments
Post a Comment