Reputation: 31
I have following scenario: I have say a Vehicle class that has several fields for each vehicle component:
public WheelBase Wheels;
public EngineBase Engine;
public TrainBase DriveTrain;
For each car component there are several classes inheriting from the base class, for example we may have: V8Engine : EngineBase, V6Engine : EngineBase, I6Engine : EngineBase, and so on.
If I want to save a car's loadout in a standard database (such as a text file), and when I need to load a car I need to know which "subtype" of component should be loaded. For example I want to load a car that has a V6Engine : EngineBase, SummerTireWheel : WheelBase, ManualTrain : TrainBase.
What's the best way to store and retrieve this information? The only way I can think of is save the name of the "subtype" in the database and use a group of switches to create the correct type of component, such as:
switch(EngineType)
{
case "V8Engine" :
Engine = new V8Engine();
break;
case "V6Engine" :
Engine = new V6Engine();
break;
case "I6Engine" :
Engine = new I6Engine();
break;
}
This method certainly works but I feel it's very ugly. Are there more elegant ways to handle this type of scenario?
Upvotes: 3
Views: 430
Reputation: 3476
I think the best way to do this it's with XML serialization and deserializtion
XmlSerializer serializer = new XmlSerializer(typeof(List<MyClass>));
using(FileStream stream = File.OpenWrite("filename"))
{
List<MyClass> list = new List<MyClass>();
serializer.Serialize(stream, list);
}
using(FileStream stream = File.OpenRead("filename"))
{
List<MyClass> dezerializedList =
(List<MyClass>) serializer.Deserialize(stream);
}
Also see this link: XML - Can not deserialize after serialize (How to serialization and deserialization with inheritance)
Upvotes: 1