奇怪的空引用异常。使用谓词时 [英] Weird nullreference exception. When using predicates
问题描述
守则解释了这一切。我试过在forEach循环中获取_dealer.Name而不使用谓词,它工作正常。但是使用Predicate ON它会开始抛出这个例外
The Code Explains it all. i have tried getting the _dealer.Name in forEach loop without using the Predicate and it works fine. But with Predicate ON it starts throwing this Exception
private void btnDealerLoadTockets_Click(object sender, EventArgs e)
{
// MainListBox.DataSource = LoadDealersList();
// And Yes , there are items in the DealersList. dlist.Count returns 5
List<Dealer> dlist = LoadDealersList();
Dealer _Dealer = dlist.Find(x => x == (Dealer)MainListBox.SelectedItem);
foreach (Dealer item in dlist)
{
if (item.name == _Dealer.name)
{
Console.WriteLine("Match Found");
}
}
}
我尝试了什么:
守则解释了这一切。我试过在forEach循环中获取_dealer.Name而不使用谓词,它工作正常。但是使用Predicate ON它会开始抛出此异常
What I have tried:
The Code Explains it all. i have tried getting the _dealer.Name in forEach loop without using the Predicate and it works fine. But with Predicate ON it starts throwing this Exception
推荐答案
您应该学会尽快使用调试器。在方法的第一行设置断点,逐行逐步检查,检查变量的值。当你不期望它时,你会很快看到哪一个null
。
最可能的原因是查找
方法返回null
,所以你得到一个NullReferenceException
当您尝试访问_Dealer
变量上的属性时。简单的解决方案是在尝试使用它之前测试变量。
You should learn to use the debugger ASAP. Set a breakpoint on the first line of your method, and step through it line by line, examining the values of the variables. You'll quickly see which one isnull
when you don't expect it to be.
The most likely cause is that theFind
method is returningnull
, so you get aNullReferenceException
when you try to access a property on the_Dealer
variable. The simple solution is to test the variable before you try to use it.
if (_Dealer != null)
{
foreach (Dealer item in dlist)
{
if (item.name == _Dealer.name)
{
Console.WriteLine("Match Found");
}
}
}
如果您的目标是确定item.name和item.name之间是否匹配列表中的Dealer.name<经销商> ...怎么样:
If your goal here is to determine if there is a match between item.name and a Dealer.name in the List<Dealer> ... how about:
if(dlist.Any(dlr => dlr.name == item.Name)
{
// whatever
}
// if you need to do something with the match:
Dealer match = dlist.FirstOrDefault(dlr => dlr.name == item.name);
// default for Reference Types is 'null
if(match == null}
{
// whatever
}
else
{
// use the match for something ?
}
真的需要知道错误信息,以找出'Find with Predicate。
Really need to know the error message to figure out what's happening with 'Find with Predicate.
这篇关于奇怪的空引用异常。使用谓词时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!