【问题标题】:IsolatedStorage best practise隔离存储最佳实践
【发布时间】:2014-02-11 13:09:31
【问题描述】:

我正在构建我的第一个 WP8 应用程序,但我遇到了疑问。

我必须在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");
            }
        }

这很好用,现在的问题是我必须对其他两个班级也这样做。

我是否必须再次编写完全相同的代码,只更改其他类的统计信息?

或者有什么更聪明的方法可以做?

【问题讨论】:

    标签: windows-phone-8 windows-phone isolatedstorage


    【解决方案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());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-05
      • 2012-11-30
      • 2012-06-26
      • 2015-10-16
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多