我有一个像这样的基类:
public class Sensor
{
public void Serialize(string path)
{
try
{
System.Xml.Serialization.XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(this.GetType());
using (System.IO.StreamWriter file = new System.IO.StreamWriter(System.IO.Path.GetFullPath(path)))
{
xml.Serialize(file, this);
}
}
catch (Exception e)
{
;
}
}
public static T Deserialize<T>(string path)
{
T loaded = default(T);
try
{
System.Xml.Serialization.XmlSerializer deserializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
using (StreamReader reader = new StreamReader(path))
{
loaded = (T)deserializer.Deserialize(reader);
}
}
catch (Exception e)
{
;
}
return loaded;
}
}
然后我从中得到了两个类:
public TemperatureSensor : Sensor {}
public PositionSensor :Sensor{}
它们共享一些通用接口,但实现方式也有所不同。
我有一个SensorController
,其中包含List<Sensor>
,其中包含不同的传感器。我想将它们保存到XML文件中,然后再加载。
我尝试了一个简单的方法:
public void Load()
{
var files = Directory.GetFiles(directory, "*.xml");
foreach(var file in files)
{
var p = CodePuzzle.Deserialize<Puzzle>(file);
}
}
问题在于,当解串器找到<PositionSensor>
时,它就会崩溃(Unexpected <PositionSensor> at 2,2
)。我想它是在期待<Sensor>
那怎么办?将每个Sensor加载到其最初存储在的子类中?
答案 0 :(得分:0)
首先,您应该将标签[XmlInclude(typeof(DerivedClass))]
添加到基本类。看起来像这样:
[Serializable]
[XmlInclude(typeof(TemperatureSensor))]
[XmlInclude(typeof(PositionSensor))]
public Class Sensor
....
然后,当您将任何派生类保存到xml文件时,将它们另存为Sensor
,而不是派生类。
var myTemp = new TemperatureSensor();
Sensor.saveToXML(myTemp,"myTemp.xml")
然后,当以Sensor的形式读取xml时,您仍然可以标识它们实际属于的子类。
Sensor myImportedSensor = Sensor.Load("myTemp.xml")
// myImportedSensor is Sebsir returns true
// AND
// myImportedSensor is TemperatureSensor returns also true