【问题标题】:Xamarin.Forms - KeyNotFoundException: The given key was not present in the dictionary C#Xamarin.Forms - KeyNotFoundException:给定的键不在字典 C# 中
【发布时间】:2020-03-12 16:05:00
【问题描述】:

我正在使用 Xamarin.Forms 并收到此错误:

KeyNotFoundException: 给定的键不在字典中

对于这一行:

bool isLogin = (bool)Application.Current.Properties["isLogin"];

我试图检查密钥是否存在:

if(Application.Current.Properties.ContainsKey("isLogin"))
            {
                bool isLogin = (bool)Application.Current.Properties["isLogin"];

                string username = Application.Current.Properties["username"].ToString();

                if (isLogin)
                {
                    Application.Current.MainPage.Navigation.PushAsync(new MenuPage(), true);
                }
            }

但是即使设置了key和value,检查key也总是返回false:

Application.Current.Properties["isLogin"] = true;

【问题讨论】:

  • 什么时候设置字典中的值?也许您在检查后设置它。请提供更多背景信息。
  • 我会在成功登录后设置它,当我再次运行应用程序时,它说它不存在
  • 当然,该字典存储在内存中,因此它会在应用程序重新启动时被销毁并重新初始化。因此,您应该将登录数据保存在本地(文件、sqlite 等)并在应用启动时从本地存储的数据中对其进行初始化,或者在登录后重新初始化应用而不重新启动它。
  • 您在简单添加之前尝试获取密钥!
  • 哦,我以为 Application.Current.Properties 在重新启动应用程序时会起作用

标签: c# xamarin.forms


【解决方案1】:

Application.Current.Properties 将存在,即使您杀死应用程序并重新启动它。只需尝试以这种方式拔下您的设备并尝试登录并检查,它就会工作。调试时它不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 2018-01-12
    • 2019-07-10
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多