【问题标题】:How to serialize an array of a base class filled with its subclasses to XML?如何将填充了其子类的基类数组序列化为 XML?
【发布时间】:2010-12-27 13:27:59
【问题描述】:

我正在尝试序列化包含一些 TestChild 对象的 Test 对象数组。

public class Test
{
    public string SomeProperty { get; set; }
}

public class TestChild : Test
{
    public string SomeOtherProperty { get; set; }
}

class Program
{
    static void Main()
    {
        Test[] testArray = new[]
        {
            new TestChild { SomeProperty = "test1", SomeOtherProperty = "test2" },
            new TestChild { SomeProperty = "test3", SomeOtherProperty = "test4" },
            new TestChild { SomeProperty = "test5", SomeOtherProperty = "test6" },
        };

        XmlSerializer xs = new XmlSerializer(typeof(Test));

        using (XmlWriter writer = XmlWriter.Create("test.xml"))
            xs.Serialize(writer, testArray);
    }
}

我收到 InvalidOperationException 说 TestChild 无法转换为 Test。

这是有道理的,但有没有办法做到这一点?

【问题讨论】:

    标签: c# xml serialization xml-serialization


    【解决方案1】:

    最简单的方法是对类进行注解,以便序列化器预测子类:

    [XmlInclude(typeof(TestChild))]
    public class Test
    {
        public string SomeProperty { get; set; }
    }
    

    否则(如果为 XmlSerializer 使用更复杂的构造函数),您需要非常小心地缓存和重用序列化程序实例 - 否则会导致内存溢出(它会为每个程序创建一个程序集)无法被垃圾收集的时间;最简单构造函数只采用Type 为您处理此缓存)。

    【讨论】:

    • 谢谢! (特别是关于缓存的建议)
    【解决方案2】:

    您可以使用proper constructor 指定已知类型,并且您正在序列化一个测试数组Test[] 而不是Test,因此构造函数的第一个参数应该是typeof(Test[])

    var xs = new XmlSerializer(typeof(Test[]), new Type[] { typeof(TestChild) });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-03
      • 1970-01-01
      • 2013-01-03
      • 2019-12-10
      • 2012-03-18
      • 1970-01-01
      • 2018-01-09
      相关资源
      最近更新 更多