Serializing / Deserializing the derived class

时间秒杀一切 提交于 2019-12-24 23:24:37

问题


I have a base class and another derived from it. Let's assume, the base class has 20 members and derived has 5 members. Only the derived class is serializable.

After I instantiate, the derived class's object has all 25 members. Now how can I only serialize the 5 members of derived class? When I use "this" to serizalize 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 any similar example. If you know one, please point me to it.

Thanks for all the help.


回答1:


Use the [NonSerializedAttribute] attribute on every field you don't want to serialize.

Or implement the ISerializsable interface and manually serialize the fields you need on the 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




回答2:


Instead of inheriting, I made the class (which can be serialized) a member of the parent class. The parent class is not a parent anymore. I will just instantiate objects of this class and it will have a member object which can be serialized.



来源:https://stackoverflow.com/questions/10637833/serializing-deserializing-the-derived-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!