c# - 序列化数据表时出现 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();
}
}
使用ClassA和ClassB类:
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# - C# 实例对象
- python - 如何重新排序 NetworkX 图中的节点?
- ansible - Ansible 无法腌制“模块”对象
- python - 错误:[Errno 13] Permission Denied with python3 virtual env
- python - 从一列开始日期和一列结束日期创建一列日期 - python
- android - 如何在android应用程序中拆分单独的音频通道
- c - 链表-在c开头插入
- python - 如何使用 Discord.py 从 token.env 获取令牌
- c++ - std::unordered_map 实际如何使用哈希函数?
- r - R中的投资组合再平衡