Serializing / Deserializing Derived Class
I have a base class and another one derived from it. Suppose the base class has 20 members and has 5 members. Only the derived class is serializable.
After I create an instance, the derived class object has all 25 members. Now, how can I only serialize 5 members of a derived class? When I use "this" to serialize or deserialize, the entire class (all 25 members) is serialized and then deserialized.
Here is a code snippet (not complete):
// Base class definition.
public abstract class baseMyClass
{
// declaration of members
}
...
// Derived class definition.
[Serializable]
public sealed class MyDerivedClass : baseMyClass
{
// declaration of members
}
...
// Serializing the object.
StringWriter writer = new StringWriter();
XmlSerializer xs = new XmlSerializer(typeof(MyDerivedClass));
xs.Serialize(writer, this);
...
// Deserializing the object.
StringReader reader = new StringReader(System.Text.Encoding.UTF8.GetString(data));
XmlSerializer xs = new XmlSerializer(typeof(MyDerivedClass));
MyDerivedClass objMyDerivedClass = (MyDerivedClass)(xs.Deserialize(reader));
I couldn't find a similar example. If you know one, please point it to me.
Thanks for the help.
source to share
Use the [NonSerializedAttribute] attribute for each field that you do not want to serialize.
Or implement the ISerializsable interface and manually serialize the desired fields in a derived class.
http://msdn.microsoft.com/en-US/library/axwwbcs6(v=vs.80 )
http://msdn.microsoft.com/en-us/library/ty01x675(v=vs.80).aspx
source to share