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

And*_*ord 4 c# settings serialization windows-store-apps

我正在将Windows Phone 8应用程序移植到Windows 8.1,并希望使用ApplicationData.Current.LocalSettings来存储/保留一些数据.除了一些String/Bool/Int值之外,我还希望存储一个(非常简单的)自定义类.

[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; }     
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在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
Run Code Online (Sandbox Code Playgroud)

使用时,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)
Run Code Online (Sandbox Code Playgroud)

我发现提示使用DataContract/DataMember,但这没有改变什么?不知道怎么解决这个问题?

And*_*ich 5

从文档(http://msdn.microsoft.com/en-us/library/windows/apps/hh464917.aspx):

您无法直接将其他类型的对象分配给应用数据.您可以将数据序列化为一种受支持的数据类型,例如,您可以将数据序列化为JSON并将其存储为字符串,但您需要处理序列化.

因此,您需要自己序列化对象或使用ApplicationDataCompositeValue进行分组.