问题
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