Reputation: 31
I am building my first WP8 application and I ran into a doubt.
I have to save in the IsolatedStorage some data obtained by serializing three different object.
My code for loading this data is this:
public static Statistics GetData()
{
Statistics data = new Statistics();
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("stats.xml", FileMode.OpenOrCreate))
{
XmlSerializer serializer = new XmlSerializer(typeof(Statistics));
data = (Statistics)serializer.Deserialize(stream);
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message + "\n" + e.InnerException);
}
return data;
}
And for saving data of course is this
public static void SaveStats(Statistics stats)
{
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Indent = true;
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("stats.xml", FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(Statistics));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))
{
serializer.Serialize(xmlWriter, stats);
}
}
}
}
catch
{
MessageBox.Show("Salvataggio non riuscito");
}
}
This works fine, now the problem is that I have to do the same also for other two classes.
Do I have to write the same exact code again, only changing Statistics with the other class?
Or there is something way more clever to do?
Upvotes: 0
Views: 62
Reputation: 964
Take a look at Generics. Your serialize method would look like this:
public static void SaveStats<T>(T obj) where T : class, new()
{
...
XmlSerializer serializer = new XmlSerializer(typeof(T));
...
}
Method invoke:
SaveStats<Statistics>(new Statistics());
SaveStats<OtherObject>(new OtherObject());
Upvotes: 1