Inheriting Serialization using the Curiously Recurring Template Pattern
I have a base class defined as follows:
public abstract class XMLBackedObject<T> where T: XMLBackedObject<T>
{
/// <summary>
/// Load the specified xml file and deserialize it.
/// </summary>
/// <param name='filePath'>
/// File path to load
/// </param>
public static T Load(string filePath)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using(FileStream stream = new FileStream(filePath, FileMode.Open))
{
return serializer.Deserialize(stream) as T;
}
}
/// <summary>
/// Save this instance to the specified file path
/// </summary>
/// <param name='filePath'>
/// File path to save to.
/// </param>
public void Save(string filePath)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using(FileStream stream = new FileStream(filePath, FileMode.Create))
{
serializer.Serialize(stream, this);
}
}
}
And classes inherit it as follows:
public class Config : XMLBackedObject<Config>
{
//...fields and methods...
}
public abstract class Command : XMLBackedObject<Command>
{
//...fields and methods...
}
public class MenuNavigationCommand : Command
{
//...no fields, only methods
}
Config's Save function executes without any hitches, but using Save on
MenuNavigationCommand gives me this error:
InvalidOperationException: The type of the argument object
'MenuChoiceCommand' is not primitive.
All I need MenuNavigationCommand to do is save the fields that exist in
the Command class it inherits from, not any new fields in
MenuNavigationCommand. Is there any way to do this? Or should I just
implement a Load and Save method on every class that uses more than one
level of inheritance?
No comments:
Post a Comment