这是一个有趣的奇怪行为(读:bug)。我的简单测试应用程序中有以下两种方法:
private void Save()
{
var settings = IsolatedStorageSettings.ApplicationSettings;
settings["foo"] = new DateTimeOffset(2012, 12, 12, 12, 12, 12, TimeSpan.Zero);
settings["bar"] = new DateTimeOffset(2011, 11, 11, 11, 11, 11, TimeSpan.Zero);
settings.Save();
}
private void Load()
{
var settings = IsolatedStorageSettings.ApplicationSettings;
string foo = settings["foo"].ToString();
string bar = settings["bar"].ToString();
}
当我运行我的应用程序时,我可以调用Save然后加载并获取保存的值。但是,当我停止应用程序,再次启动并尝试加载时,有第一次机会InvalidOperationException
(在ApplicationSettings
属性内),然后设置对象为空(我的值丢失) 。例外情况说:
类型'System.DateTimeOffset'无法添加到已知类型列表中,因为已存在具有相同数据协定名称“http://schemas.datacontract.org/2004/07/System:DateTimeOffset”的其他类型“System.Runtime.Serialization.DateTimeOffsetAdapter”。
当我使用ISETool.exe查看已保存到_ApplicationSettings
文件的内容时,我可以看到有两个DateTimeOffset
类型引用,这可能是问题所在。换句话说,IsolatedStorageSettings.Save()
会创建一个以后无法加载的损坏文件。
如果我将其他类型保存到“bar”设置,一切正常。只有在保存两个或更多DateTimeOffset值时才会出现此问题。作为一种解决方法,我可以将手动序列化的所有DateTimeOffset值保存为字符串。我想避免这种情况。
答案 0 :(得分:3)
您似乎确实发现了AppliationSettings对象的错误。如果您打算在ApplicationSettings中存储DateTimeOffset值,那么这种方法将起作用。
使用您的设置创建一个类:
public class MyAppSettings
{
public DateTimeOffset Foo { get; set; }
public DateTimeOffset Bar { get; set; }
}
按如下方式更改方法:
private void Save()
{
Collection<MyAppSettings> myAppSettings = new Collection<MyAppSettings>();
myAppSettings.Add(new MyAppSettings
{
Foo = new DateTimeOffset(2012, 12, 12, 12, 12, 12, TimeSpan.Zero),
Bar = new DateTimeOffset(2011, 11, 11, 11, 11, 11, TimeSpan.Zero)
});
IsolatedStorageSettings.ApplicationSettings["MyAppSettings"] = myAppSettings;
}
private void Load()
{
Collection<MyAppSettings> myAppSettings = (Collection<MyAppSettings>)IsolatedStorageSettings.ApplicationSettings["MyAppSettings"];
string foo = myAppSettings.First().Foo.ToString();
string bar = myAppSettings.First().Bar.ToString();
}
但是,我会阅读这个答案,了解在您自己的设置文件中存储此类信息的技术。 windows phone 7 IsolatedStorageSettings.ApplicationSettings complex data
此外,您可以更简单地处理此问题,并通过更改Save和Load方法避免使用Collection,如下所示。
private void Save()
{
MyAppSettings myAppSettingsSimple = new MyAppSettings
{
Foo = new DateTimeOffset(2012, 12, 12, 12, 12, 12, TimeSpan.Zero),
Bar = new DateTimeOffset(2011, 11, 11, 11, 11, 11, TimeSpan.Zero)
};
IsolatedStorageSettings.ApplicationSettings["MyAppSettingsSimple"] = myAppSettingsSimple;
}
private void Load()
{
MyAppSettings myAppSettingsSimple = (MyAppSettings)IsolatedStorageSettings.ApplicationSettings["MyAppSettingsSimple"];
txtFoo.Text = myAppSettingsSimple.Foo.ToString();
txtBar.Text = myAppSettingsSimple.Bar.ToString();
}