gpt4 book ai didi

C# 列表<> 到 xml

转载 作者:数据小太阳 更新时间:2023-10-29 01:47:14 28 4
gpt4 key购买 nike

打电话

List<PC> _PCList = new List<PC>();
...add Pc to PCList..
WriteXML<List<PC>>(_PCList, "ss.xml");

函数

public static void WriteXML<T>(T o, string filename)
{

string filePath= Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Genweb2\\ADSnopper\\" + filename;

XmlDocument xmlDoc = new XmlDocument();
XPathNavigator nav = xmlDoc.CreateNavigator();
using (XmlWriter writer = nav.AppendChild())
{
XmlSerializer ser = new XmlSerializer(typeof(List<T>), new XmlRootAttribute("TheRootElementName"));
ser.Serialize(writer, o); // error
}
File.WriteAllText(filePath,xmlDoc.InnerXml);

}

内部异常

Unable to cast object of type 'System.Collections.Generic.List1[PC]' to type
'System.Collections.Generic.List
1[System.Collections.Generic.List`1[PC]]'.

请帮忙

最佳答案

问题出在线路上

XmlSerializer ser = new XmlSerializer(typeof(List<T>), ...

你的 T已经是List<PC> ,而您正在尝试创建 typeof(List<T>) , 这将转换为 typeof(List<List<PC>>) .简单地制作它typeof(T)相反。

关于C# 列表<> 到 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12596909/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com