全部——我的一个类中有这两种方法:
public static void DeSerializeFromXml(out cDBData db, string pathToXML)
{
using (XmlTextReader reader = new XmlTextReader(pathToXML))
{
XmlSerializer ser = new XmlSerializer(typeof(cDBData));
db = (cDBData)ser.Deserialize(reader);
}
}
public static void DeSerializeFromXml(out cDatabases db, string pathToXML)
{
using (XmlTextReader reader = new XmlTextReader(pathToXML))
{
XmlSerializer ser = new XmlSerializer(typeof(cDatabases));
db = (cDatabases)ser.Deserialize(reader);
}
}
他们工作正常,但我想知道为什么我不能根据方法的返回类型创建方法重载。我以为我读到这在某处是可能的,但我显然错了,因为它不起作用:
public static cDBData DeSerializeFromXml(string pathToXML)
{
cDBData db;
using (XmlTextReader reader = new XmlTextReader(pathToXML))
{
XmlSerializer ser = new XmlSerializer(typeof(cDBData));
db = (cDBData)ser.Deserialize(reader);
}
return db;
}
public static cDatabases DeSerializeFromXml(string pathToXML)
{
cDatabases db;
using (XmlTextReader reader = new XmlTextReader(pathToXML))
{
XmlSerializer ser = new XmlSerializer(typeof(cDatabases));
db = (cDatabases)ser.Deserialize(reader);
}
return db;
}
感谢您的周到回复
感谢 dlev,这是最终的解决方案
public static T DeSerializeFromXml<T>(string pathToXML)
{
T db;
using (XmlTextReader reader = new XmlTextReader(pathToXML))
{
XmlSerializer ser = new XmlSerializer(typeof(T));
db = (T)ser.Deserialize(reader);
}
return db;
}
public static void SerializeToXml<T>(T db, string pathToXML)
{
using (var fileStream = new FileStream(pathToXML, FileMode.Create))
{
var ser = new XmlSerializer(typeof(T));
ser.Serialize(fileStream, db);
}
}
我想在搜查警察关闭这个问题之前把这些贴出来。