【问题标题】:How to store custom class to LocalSettings in Windows Store App?如何将自定义类存储到 Windows Store App 中的 LocalSettings?
【发布时间】:2014-03-10 13:36:23
【问题描述】:

我正在将 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 的提示,但这并没有改变任何东西?知道如何解决这个问题吗?

【问题讨论】:

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


    【解决方案1】:

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

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

    所以需要自己序列化对象或者使用ApplicationDataCompositeValue进行分组。

    【讨论】:

      猜你喜欢
      • 2017-10-24
      • 2015-04-26
      • 2014-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-10
      • 2023-04-03
      相关资源
      最近更新 更多