gpt4 book ai didi

c# - 当我在 Xamarin 表单中使用 Application.Current.SavePropertiesAsync 时,列表不会被保存

转载 作者:行者123 更新时间:2023-12-04 05:03:00 24 4
gpt4 key购买 nike

我目前正在尝试在 Xamarin 表单中保存列表。我使用这个代码片段:

var list = new List<myClass> ();

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

当我关闭应用程序并使用此代码时...

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

}

...我无法访问此 if 语句。

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

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

...应用程序崩溃。

我看到有一个名为“设置”的插件,如果没有解决此问题的方法,我可能需要使用它,但如果可能的话,我更愿意使用我当前的代码。

最佳答案

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

表示不能保存List因为它不是原始类型的对象。
您可以将其序列化为 JSON 字符串,然后它就可以工作了。
代码示例:

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

不要忘记将 JSON 反序列化为 List<string>加载值时。

请注意 yourList.ToString()在这种情况下将不起作用。更多信息 here .

P.S.:熟悉 official documentation并在另一个related thread上查看此帖子.

关于c# - 当我在 Xamarin 表单中使用 Application.Current.SavePropertiesAsync 时,列表不会被保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43573544/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com