I have a base class like :
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;
}
}
Then I have a couple of classes that derive from this:
public TemperatureSensor : Sensor {}
public PositionSensor :Sensor{}
They share some common interfaces but also implement things differently.
I have a SensorController
that contains a List<Sensor>
with a mixture of different sensors. I want to save them to XML files and load them afterwards.
I tried a simple:
public void Load()
{
var files = Directory.GetFiles(directory, "*.xml");
foreach(var file in files)
{
var p = CodePuzzle.Deserialize<Puzzle>(file);
}
}
The problem is that when the deserializer finds the <PositionSensor>
it crashes (Unexpected <PositionSensor> at 2,2
).. I guess it was expecting <Sensor>
How can that be done?? Loading each Sensor in the sub-class it was originally stored in??