C# IsolatedStorageSettings.ApplicationSettings无法在先前存储的两个DateTimeOffset对象之后加载设置
下面是一个有趣的奇怪行为(读:bug)。在我的简单测试应用程序中,我有以下两种方法:C# IsolatedStorageSettings.ApplicationSettings无法在先前存储的两个DateTimeOffset对象之后加载设置,c#,windows-phone-8,C#,Windows Phone 8,下面是一个有趣的奇怪行为(读:bug)。在我的简单测试应用程序中,我有以下两种方法: private void Save() { var settings = IsolatedStorageSettings.ApplicationSettings; settings["foo"] = new DateTimeOffset(2012, 12, 12, 12, 12, 12, TimeSpan.Zero); settings["bar"
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,然后加载并获取保存的值。但是,当我停止应用程序,再次启动它并尝试加载时,第一个机会是invalidoOperationException
(在ApplicationSettings
属性中),然后设置对象为空(我的值丢失)。例外情况是:
无法将类型“System.DateTimeOffset”添加到已知类型列表中,因为已存在具有相同数据协定名称“”的另一类型“System.Runtime.Serialization.DateTimeOffsetAdapter”
当我使用ISETool.exe查看保存到\u ApplicationSettings
文件中的内容时,我可以看到有两个DateTimeOffset
类型引用,这可能就是问题所在。换句话说,IsolatedStorageSettings.Save()
创建了一个损坏的文件,以后无法加载
如果我将不同的类型保存到“bar”设置,则一切正常。只有在保存两个或多个DateTimeOffset值时,才会出现此问题。作为一种解决方法,我可以将手动序列化的所有DateTimeOffset值保存为字符串。不过,我想避免这种情况。看起来您确实发现了applicationsettings对象的一个bug。如果您打算在应用程序设置中存储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();
}
有趣的观察。我想这里的问题是“这个问题有没有更好的解决办法?”谢谢Rob。我想你是在建议我创建一个类来包装我需要保存的所有设置,然后在一次赋值中将一个实例保存到
ApplicationSettings
。不过,您的代码有点不清楚。是否有理由保存一个集合,然后使用First()获取所需的内容?没有特别的理由使用集合。在使用设置信息时,最终需要集合的情况并不少见。我对这篇文章进行了编辑,使其包含了相同的基本方法,但没有收集。
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();
}