好的,所以我有一个类型:
public class MonitorConfiguration
{
private string m_sourcePath;
private string m_targetPath;
public string TargetPath
{
get { return m_targetPath; }
set { m_targetPath = value; }
}
public string SourcePath
{
get { return m_sourcePath; }
set { m_sourcePath = value; }
}
//need a parameterless constructor, just for serialization
private MonitorConfiguration()
{
}
public MonitorConfiguration(string source, string target)
{
m_sourcePath = source;
m_targetPath = target;
}
}
当我序列化和反序列化这些列表时,像这样
XmlSerializer xs = new XmlSerializer(typeof(List<MonitorConfiguration>));
using (Stream isfStreamOut = isf.OpenFile("Test1.xml", FileMode.Create))
{
xs.Serialize(isfStreamOut, monitoringPaths);
}
using (Stream isfStreamIn = isf.OpenFile("Test1.xml", FileMode.Open))
{
monitoringPaths = xs.Deserialize(isfStreamIn) as List<MonitorConfiguration>;
}
一切正常。
但是,我真的想隐藏属性的公共设置器。这可以防止它们被 XML 序列化程序序列化。所以,我实现了我自己的,像这样:
将类声明更改为:public class MonitorConfiguration : IXmlSerializable
并添加以下内容:
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
//make sure we read everything
while (reader.Read())
{
//find the first element we care about...
if (reader.Name == "SourcePath")
{
m_sourcePath = reader.ReadElementString("SourcePath");
m_targetPath = reader.ReadElementString("TargetPath");
// return;
}
}
}
public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteElementString("SourcePath", m_sourcePath);
writer.WriteElementString("TargetPath", m_targetPath);
}
这似乎可行,但是,我只从列表中取出第一个项目,所有其他项目都被遗忘了。我已经尝试过使用和不使用当前注释掉的返回。我在这里做错了什么?
需要注意的是,这只是说明问题的一段代码;我使用的 XML 序列化技术仅限于我的永恒技工。