Xamarin表单中使用Application.Current.SavePropertiesAsync时,列表未保存 [英] List does not get saved when I use Application.Current.SavePropertiesAsync in Xamarin forms

查看:302
本文介绍了Xamarin表单中使用Application.Current.SavePropertiesAsync时,列表未保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试以Xamarin形式保存列表.我使用以下代码段:

I am currently trying to save a list in Xamarin forms. I use this code snippet:

var list = new List<myClass> ();

Application.Current.Properties["myList"] = list;
await Application.Current.SavePropertiesAsync();

然后我关闭应用程序并使用此代码...

When I then close the app and use this code...

if (Application.Current.Properties.ContainsKey("myList"))
{

}

...我无法达到此if语句.

...I cannot reach this if statement.

我读到一些关于人们在使用此解决方案保存列表时遇到的问题,但是他们通过将其转换为字符串来解决了问题.我不确定如何执行此操作.如果我这样做...

I read something about people having issues saving a list with this solution but they solved it by converting it to a string. I am a bit unsure on how to do this. If I do this...

Application.Current.Properties["myList"] = list.ToString();

...应用程序崩溃.

...the app crashes.

我看到有一个名为"Settings"的插件,如果无法解决此问题,我可能需要使用它,但如果可能的话,我希望使用我的当前代码.

I saw that there is a plugin called "Settings" that I might need to use instead in case there isn't a solution to this problem but I would prefer to work with my current code if possible.

推荐答案

属性字典只能序列化以下类型的原始类型 贮存.尝试存储其他类型(例如List可以 默默地失败).

The Properties dictionary can only serialize primitive types for storage. Attempting to store other types (such as List can fail silently).

这意味着您不能保存List,因为它不是原始类型的对象.
例如,您可以将其序列化为JSON字符串,然后它将起作用.
代码示例:

It means that you can't save List because it's not a primitive type of object.
You can serialize it to JSON string for example then it will work.
Code example:

var jsonValueToSave = JsonConvert.SerializeObject(myList);
Application.Current.Properties["myList"] = jsonValueToSave;
await Application.Current.SavePropertiesAsync();

在将值重新加载回原值时,别忘了将JSON反序列化为List<string>.

Don't forget to deserialize JSON to List<string> when loading the value back.

请注意,在这种情况下,yourList.ToString()将不起作用.详细信息此处.

Note that yourList.ToString() will not work in this case. More info here.

PS:熟悉官方文档在另一个相关主题上查看此帖子.

P.S.: Get familiar with the official documentation & check this post on another related thread.

这篇关于Xamarin表单中使用Application.Current.SavePropertiesAsync时,列表未保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆