本文介绍了XMLSerialization:参数对象“ Sw”的类型不是基本类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将对象序列化为XML文件,但是遇到了以上错误。

I'm trying to serialize an object to an XML file, but am getting the above error.

问题似乎出在包含包含以下内容的对象的问题上一个基类,但由从该基类派生的对象填充。

The problem seems to be with objects that contain a list of a base class but is populated by objects derived from the base class.

示例代码如下:

public class myObject
{
    public myObject()
    {
        this.list.Add(new Sw());
    }

    public List<Units> list = new List<Units>();
}

public class Units
{
    public Units()
    {
    }
}

public class Sw : Units
{
    public Sw();
    {
    }

    public void main()
    {
        myObject myObject = new myObject();
        XmlSerializer serializer = new XmlSerializer(typeof(myObject));
        TextWriter textWriter = new StreamWriter ("file.xml");
        serializer.Serialize (textWriter, myObject);
    }

例如一个仅包含 List< Units> 的对象,该对象由从 Units 类继承的派生对象填充( code> Sw )。

E.g. an object that contains only a List<Units> which is populated by derived objects which inherit from the Units class (Sw).

抱歉,没有提供我的实际代码,但是涉及的对象非常复杂,这似乎是

Sorry for not providing my actual code but the objects involved are quite complex and this seems to be the only part of the object which wont successfully be serialized - and only when the list contains the derived classes.

如何正确地序列化这样的类?

How can I correctly serialize a class like this?

推荐答案

XmlInclude Units 类c>将您的派生类作为参数传递的属性:

Mark Units class with XmlInclude attribute passing your derived class as parameter:

[XmlInclude(typeof(Sw))]
public class Units
{
    public Units()
    {
    }
}

这篇关于XMLSerialization:参数对象“ Sw”的类型不是基本类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:07