Xml Serialisation - Default Constructor

时间秒杀一切 提交于 2019-12-25 13:15:38

问题


I have a number of classes which derive from an abstract base class. These derived classes need to be serialised to XML however, they do not have a parameter-less constructor. There are a large number of derived class, so I would prefer not to have to go back and add a parameter-less constructor to them all.

I am hoping there's something I can do with the base class that will allow them to be serialised without having to modify each individual class. Anyone got any idea's on how this can be achieved?

Here's a basic example of the classes:

public abstract class MyBase
{
    internal MyBase()
    { }

    //Various abstract properties here
}

public class MyDerivedClass : MyBase
{
    //Various methods/Properties here
}

回答1:


The biggest problem you will have, is that you can't deserialise an instance of MyBase because it is abstract. This means you're going to need to do something about how the classes will be constructed.

It might be the case that you need to just take the hit and add an appropriate constructor, either a parameterless one and rely on the default [Serializable] attribute, or customise how the class is serialised by implementing ISerializable.



来源:https://stackoverflow.com/questions/7228216/xml-serialisation-default-constructor

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