2014-02-11 28 views
0

我正在构建我的第一个WP8应用程序,并且遇到了疑问。IsolatedStorage最佳实践

我必须在IsolatedStorage中保存一些通过序列化三个不同对象获得的数据。

我加载此数据的代码是这样的:

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; 
    } 

以及保存过程中的数据是这样的

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"); 
      } 
     } 

这工作得很好,现在的问题是,我必须做同样的也适用于其他两个班级。

我是否必须重新编写相同的确切代码,只更改其他类的统计信息?

还是有什么办法更聪明?

回答

1

看看Generics。 你的序列化方法是这样的:

public static void SaveStats<T>(T obj) where T : class, new() 
{ 
    ... 
    XmlSerializer serializer = new XmlSerializer(typeof(T)); 
    ... 
} 

方法来调用:

SaveStats<Statistics>(new Statistics()); 
SaveStats<OtherObject>(new OtherObject()); 
+0

你是保护人类生命,它的工作非常非常感谢! – user2878912

+0

很高兴我能帮忙:) –