簡體   English   中英

如何將自定義類存儲到Windows應用商店應用中的LocalSettings?

[英]How to store custom class to LocalSettings in Windows Store App?

我正在將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,但這沒有改變什么? 不知道怎么解決這個問題?

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

您無法直接將其他類型的對象分配給應用數據。 您可以將數據序列化為一種受支持的數據類型,例如,您可以將數據序列化為JSON並將其存儲為字符串,但您需要處理序列化。

因此,您需要自己序列化對象或使用ApplicationDataCompositeValue進行分組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM