如何将自定义类存储到Windows Store应用的LocalSettings中?

5

我正在将一个Windows Phone 8应用移植到Windows 8.1,并希望使用ApplicationData.Current.LocalSettings来存储/持久化一些数据。除了一些字符串/布尔/整数值,我还想存储一个(非常简单的)自定义类。

[DataContract]
public class MyClass {
    [DataMember]
    public double Property1;

    [DataMember]
    public int Property2;

    [DataMember]
    public int Property3;

    [DataMember]
    public bool Property4;


    public int Total{
        get { return Property2 + Property 3; }     
        }
    }
}

在WP 8中,我使用IsolatedStorageSettings.ApplicationSettings来存储设置,没有任何问题。即使我不使用DataContract/DataMember,它也可以正常工作:
MyClass mySettings = new MyClass();
mySettings.Property2 = 1;
mySettings.Property2 = 2;
IsolatedStorageSettings.ApplicationSettings["mySettings"] = mySettings;
IsolatedStorageSettings.ApplicationSettings.Save();

MyClass loadedSettings = IsolatedStorageSettings.ApplicationSettings["mySettings"];
Debug.WriteLine(loadedSettings.Total); // == 3

在Win 8.1上使用以下代码会导致序列化异常:
...
ApplicationData.Current.LocalSettings.Values["mySettings"] = mySettings;


Error trying to serialize the value to be written to the application data store
  at System.Runtime.InteropServices.WindowsRuntime.IMap`2.Insert(K key, V value)
  at System.Runtime.InteropServices.WindowsRuntime.MapToDictionaryAdapter.Insert[K,V](IMap`2 _this, K key, V value)
  at System.Runtime.InteropServices.WindowsRuntime.MapToDictionaryAdapter.Indexer_Set[K,V](K key, V value)

我发现使用DataContract/DataMember的提示,但这并没有改变什么。有什么解决办法吗?
1个回答

6

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接