Xml 序列化 - 默认构造函数 [英] Xml Serialisation - Default Constructor

查看:26
本文介绍了Xml 序列化 - 默认构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多从抽象基类派生的类.这些派生类需要序列化为 XML,但是它们没有无参数构造函数.有大量的派生类,所以我宁愿不必回去为它们添加一个无参数的构造函数.

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?

以下是类的基本示例:

public abstract class MyBase
{
    internal MyBase()
    { }

    //Various abstract properties here
}

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

推荐答案

您将遇到的最大问题是,您无法反序列化 MyBase 的实例,因为它是抽象的.这意味着您将需要对如何构造类做一些事情.

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.

在这种情况下,您可能只需要添加一个合适的构造函数,要么是无参数构造函数,要么依赖默认的 [Serializable] 属性,或者自定义类的序列化方式通过实现 ISerializable.

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.

这篇关于Xml 序列化 - 默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆