【发布时间】: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