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

时间:2014-02-12 09:54:13

标签: c# serialization windows-store-apps settings

我正在将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; }     
        }
    }
}

在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 个答案:

答案 0 :(得分:5)

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

  

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

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