the*_*man 7 c# xml xmlserializer
调用
List<PC> _PCList = new List<PC>();
...add Pc to PCList..
WriteXML<List<PC>>(_PCList, "ss.xml");
Run Code Online (Sandbox Code Playgroud)
功能
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);
}
Run Code Online (Sandbox Code Playgroud)
内在的例外
无法转换类型为'System.Collections.Generic.List
1[PC]' to type 'System.Collections.Generic.List
1 [System.Collections.Generic.List`1 [PC]]'的对象.
请帮忙
问题在于线路
XmlSerializer ser = new XmlSerializer(typeof(List<T>), ...
Run Code Online (Sandbox Code Playgroud)
你T
已经List<PC>
,并且你正在尝试创建typeof(List<T>)
,这将转化为typeof(List<List<PC>>)
.简单地typeof(T)
说吧.