首页 > 解决方案 > 序列化数据表时出现 InvalidOperationException

问题描述

我尝试使用内置的WriteXml方法将DataTable对象序列化为 XML 文件。所以我的DataTable看起来像这样:

   class Program
{
    static void Main(string[] args)
    {
        DataTable dataTable = new DataTable();
        dataTable.Columns.Add("ACol", typeof(int));
        dataTable.Columns.Add("BCol", typeof(object));

        DataRow workRow1 = dataTable.NewRow();

        List<ClassA> listClassA = new List<ClassA>();
        List<ClassB> listClassB = new List<ClassB>();

        // Create some data
        for (int i = 0; i < 20; i++)
        {
            listClassA.Add(new ClassA { Prop1 = i, Prop2 = (i * i).ToString() });
            listClassB.Add(new ClassB { Prop3 = i.ToString(), Prop4 = i / 3 });

        }

        workRow1["ACol"] = 20;
        workRow1["BCol"] = listClassA;

        DataRow workRow2 = dataTable.NewRow();

        workRow2["ACol"] = 20;
        workRow2["BCol"] = listClassB;

        // Add rows to the datatable
        dataTable.Rows.Add(workRow1);
        dataTable.Rows.Add(workRow2);

        // Serialize the Class
        dataTable.TableName = "MyTable";
        dataTable.WriteXml("myTableSerialized.xml");

        // Free ressources
        dataTable.Dispose();

    }
}

使用ClassAClassB类:

public class ClassA : IXmlSerializable
{
    public int Prop1 { get; set; }

    public string Prop2 { get; set; }

    public XmlSchema GetSchema() => null;

    public void ReadXml(XmlReader reader)
    {
        reader.MoveToContent();
        reader.ReadElementContentAsInt("Prop1", "");
        reader.ReadElementContentAsString("Prop2", "");
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteElementString("Prop1", Prop1.ToString());
        writer.WriteElementString("Prop1", Prop2);
    }
}

public class ClassB : IXmlSerializable
{
    public string Prop3 { get; set; }
    public double Prop4 { get; set; }

    public XmlSchema GetSchema() => null;

    public void ReadXml(XmlReader reader)
    {
        reader.MoveToContent();
        reader.ReadElementContentAsInt("Prop3", "");
        reader.ReadElementContentAsDouble("Prop4", "");
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteElementString("Prop3", Prop3);
        writer.WriteElementString("Prop4", Prop4.ToString());
    }
}

它们都实现了 IXmlSerializable 接口。

因此,当我运行程序时,我得到System.InvalidOperationException,因为类型'System.Collections.Generic.List`1没有实现 IXmlSerializable 接口。

如何解决这个问题?

标签: c#datatable

解决方案


推荐阅读