我无法保存到隔离存储?

我正在尝试将模型保存在独立存储中:

var settings = IsolatedStorageSettings.ApplicationSettings; CurrentPlaceNowModel model = new CurrentPlaceNowModel(); settings.TryGetValue("model", out model); if (model == null) { MessageBox.Show("NULL"); settings.Add("model", new CurrentPlaceNowModel()); settings.Save(); } else MessageBox.Show("NOT NULL"); 

当我启动emu i ofcourse时“NULL”,但是如果我关闭emu上的应用程序并从菜单中再次启动它(为什么我在Visual Studio中再次启动它),为什么还要继续使用它。

第二次我不应该得到“NOT NULL”吗?

我会以不同的方式执行此操作并进行特定检查以查看密钥是否存在。

 CurrentPlaceNowModel model; using (var settings = IsolatedStorageSettings.ApplicationSettings) { if (settings.Contains("MODEL")) { model = settings["MODEL"] as CurrentPlaceNowModel; } else { model = new CurrentPlaceNowModel(); settings.Add("MODEL", model); settings.Save(); } } 

使用IsolatedStorage的这种模式肯定有效。

这不起作用的唯一原因是如果无法使用DataContractSerializer序列化CurrentPlaceNowModel 。 这是ApplicationSettings在内部用于序列化对象的内容。
您可以通过这种方式自行测试来测试这一点,看看会发生什么。

我刚刚注意到你做错了什么:

 if (model == null) { MessageBox.Show("NULL"); settings.Add("model", model); } 

这将等同于调用settings.Add("model", null) – 那么您希望以后如何获得非空值? 我怀疑你想要:

 CurrentPlaceNowModel model; if (!settings.TryGetValue("model", out model)) { model = new CurrentPlaceNowModel(); settings.Add("model", model); }