序列化/反序列化派生类 [英] Serializing / Deserializing the derived class
问题描述
我有一个基类,另一个是从基类派生的。假设基类有20个成员,派生有5个成员。
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.
实例化之后,派生类的对象具有全部25个成员。现在如何只序列化派生类的5个成员?当我使用 this进行序列化或反序列化时,整个类(所有25个成员)都将被序列化然后反序列化。
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.
感谢所有帮助。
推荐答案
我使类(可以序列化)成为父类的成员,而不是继承。父类不再是父类。我将实例化此类的对象,并且它将具有可以序列化的成员对象。
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.
这篇关于序列化/反序列化派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!