问题描述
我遇到以下代码的问题:
i got a Problem with this following Code:
string name = (string)PhoneApplicationService.Current.State["name"];
names.Add(name);
InitializeComponent();
List.ItemsSource = names;
作者:
string name = (string)PhoneApplicationService.Current.State["name"];
我收到错误消息:
System.Collections.Generic.KeyNotFoundException"类型的异常发生在 mscorlib.ni.dll 中,但未在用户代码中处理
代码在 C# 中.我尝试使用来自其他页面的 Variabel.我如何询问变量是否为未找到"应用程序跳转到另一个页面?我该如何解决问题?
The Code is in C#.I try to use an Variabel from the othe Page.How can i ask if the variable is "Not found" that the app jump to the other Page?How can i solve the Problem?
推荐答案
如果想在阅读之前先知道key是否存在,可以使用ContainsKey
方法:
If you want to know whether the key exists before reading it, you can use the ContainsKey
method:
if (PhoneApplicationService.Current.State.ContainsKey("name"))
{
string name = (string)PhoneApplicationService.Current.State["name"];
names.Add(name);
InitializeComponent();
List.ItemsSource = names;
}
else
{
// Whatever
}
此外,您似乎想在找不到密钥时导航到另一个页面.对 InitializeComponent
的调用表明您正在执行页面构造函数中的代码.如果您尝试从构造函数中使用 NavigationService,则会出现 NullReferenceException.将代码移动到 Loaded
事件,或覆盖 OnNavigatedTo
方法.
Also, you seem to want to navigate to another page when the key isn't found. The call to InitializeComponent
shows that you're executing the code in the page constructor. If you try to use the NavigationService from the constructor, you will have a NullReferenceException. Move the code to the Loaded
event, or override the OnNavigatedTo
method.
这篇关于Windows Phone 中的 System.Collections.Generic.KeyNotFoundException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!