序列化List <string>时出错

时间:2015-06-08 17:19:22

标签: c# serialization windows-runtime windows-phone-8.1

正在开发Windows Phone Runtime应用程序,我在字符串列表中有数据。但是,当我暂停我的应用程序时,错误发生Error trying to serialize the value to be written to the application data storeAdditional information: Data of this type is not supported.它表示不支持字符串列表,是否有人知道我如何修复它?

OnLaunched:

protected override void OnLaunched(LaunchActivatedEventArgs e)
{
   if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
       if (ApplicationData.Current.LocalSettings.Values.ContainsKey("lista"))
       {
          lista = (List<string>)    (ApplicationData.Current.LocalSettings.Values["lista"]);
       }       
}

OnSuspended:

private async void App_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
    {
       ApplicationData.Current.LocalSettings.Values["lista"] = App.lista;
    }

App.lista是在app.xaml.cs上声明的列表,如public static List<string> lista = new List<string>();

1 个答案:

答案 0 :(得分:1)

您必须自己序列化/反序列化列表,例如:

string Serialize(List<string> list)
{
    StringBuilder result = new StringBuilder();

    foreach (string s in list)
    {
        result.AppendFormat("{0}{1}", result.Length > 0 ? "," : "", s);
    }

    return result.ToString();
}

List<string> Deserialize(string s)
{
    return new List<string>(s.Split(','));
}

如果您的字符串可能包含逗号,请相应地编码。