使用XmlSerializer的序列化派生类 [英] Using XmlSerializer to serialize derived classes

查看:136
本文介绍了使用XmlSerializer的序列化派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的XMLSerializer序列化,它包含一个通用的列表的对象

I'm using XMLSerializer to serialize an object that contains a generic list

列表< ChildBase>儿童{获得;设置}

的问题是,每个元素从 ChildBase 派生这实际上是一个抽象类。
当我尝试反序列化,我得到一个InvalidOperationException

The problem is that each element derives from ChildBase which in fact is an abstract class. When I try to deserialize, I get an invalidOperationException

有没有一种方法,我可以使用的XMLSerializer与派生的对象?
谢谢

Is there a way I can use XMLSerializer with derived objects? Thanks.

推荐答案

有这样三种方式;要么你可以使用 [XmlInclude] 针对类型,也可以使用的XmlElement / XmlArrayItem 对财产。他们都是如下所示;注释你喜欢的对:

There are three ways of doing this; either you can use [XmlInclude] against the type, or you can use XmlElement/XmlArrayItem against the property. They are all shown below; uncomment the pair you prefer:

using System;
using System.Collections.Generic;
using System.Xml.Serialization;
public class MyWrapper {
    //2: [XmlElement("A", Type = typeof(ChildA))]
    //2: [XmlElement("B", Type = typeof(ChildB))]
    //3: [XmlArrayItem("A", Type = typeof(ChildA))]
    //3: [XmlArrayItem("B", Type = typeof(ChildB))]
    public List<ChildClass> Data { get; set; }
}
//1: [XmlInclude(typeof(ChildA))]
//1: [XmlInclude(typeof(ChildB))]
public abstract class ChildClass {
    public string ChildProp { get; set; }
}
public class ChildA : ChildClass {
    public string AProp { get; set; }
}
public class ChildB : ChildClass {
    public string BProp { get; set; }
}
static class Program {
    static void Main() {
        var ser = new XmlSerializer(typeof(MyWrapper));
        var obj = new MyWrapper {
            Data = new List<ChildClass> {
                new ChildA { ChildProp = "abc", AProp = "def"},
                new ChildB { ChildProp = "ghi", BProp = "jkl"}}
        };
        ser.Serialize(Console.Out, obj);
    }
}

这篇关于使用XmlSerializer的序列化派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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