How can I redefine deserialization in C #

I have a class that will change over time. Data from this class is serialized and deserialized as part of the launch of my application. The problem is that if I update the class by adding more properties and then run the application, the old data does not load properly.
What I want to do is to redefine the deserialization step, I do not mind manually reconstructing the object from xml, since I have a version number and I can use it to recursively update versions of the object.

Is there an interface that I can implement, or an attribute that I can set somewhere to do this?

If you cannot come up with a way to do what I want, are there any alternatives? such as default values ​​for properties that may not exist in the xml version that I am loading.

+4
source share
4 answers

Typically, for version control, you can use the OptionalField attribute for newly added members, which can cause compatibility issues. During serialization, if a member has not been serialized, it leaves the member value as null, and does not throw an exception.

Also check out the IDeserializationCallback.OnDeserialization interface, which lets you customize deserialization.

+2
source
+5
source

If this is the xml serialization you are talking about, you should implement the IXmlSerializable interface. If this is binary serialization, you can simply mark the new members with the OptionalField attribute.

You can read more here: http://msdn.microsoft.com/en-us/library/ms229752(VS.80).aspx

+1
source

You can implement an ISerializable interface and provide a constructor that accepts SerializationInfo and StreamingContext to gain control over the serialization / deserialization process. / P>

For instance:

 [Serializable] public struct MyStruct: ISerializable { private readonly int _x; private readonly int _y; // normal constructor public MyStruct(int x, int y) : this() { _x = x; _y = y; } // this constructor is used for deserialization public MyStruct(SerializationInfo info, StreamingContext text) : this() { _x = info.GetInt32("X"); _y = info.GetInt32("Y"); } public int X { get { return _x; } } public int Y { get { return _y; } } // this method is called during serialization [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("X", X); info.AddValue("Z", Y); } } 
0
source

All Articles