gpt4 book ai didi

C# 在处理列表时给出 NullReferenceException

转载 作者:太空宇宙 更新时间:2023-11-03 22:12:12 24 4
gpt4 key购买 nike

以下代码在处理时给出了 NullReferenceException。谁能告诉我为什么会这样,以及如何解决?提前致谢!这可能是一件非常简单的事情,我在某处失踪了。

if (a.Count != 0)
{
foreach(DataGridViewRow row in a )
{
foreach (DataGridViewRow newrow in b)
{
if( row.Cells[0].Value.ToString() == newrow.Cells[0].Value.ToString() &&
row.Cells[1].Value.ToString() == newrow.Cells[1].Value.ToString()) // this is the line that gives the error.
{
a.Remove(row);
}
}
}
}

这两个列表已在类的顶部声明,所以我不知道为什么会出现此错误。

 List<DataGridViewRow> a = new List<DataGridViewRow>();

List<DataGridViewRow> b = new List<DataGridViewRow>();

按照建议,我尝试使用 for 循环位,它仍然给出相同的异常

这是代码

if (a.Count != 0)
{
for (int i = a.Count - 1; i >= 0; i--)
{

int index1 = i;


for (int k = 0; k < b.Count; k++)
{
int index2 = k;

if (a.ElementAt<DataGridViewRow> (index1).Cells[0].Value.ToString() == b.ElementAt<DataGridViewRow>(index2).Cells[0].Value.ToString() && a.ElementAt<DataGridViewRow>(index1).Cells[1].Value.ToString() == b.ElementAt<DataGridViewRow>(index2).Cells[1].Value.ToString())
{

a.RemoveAt(index1);

}
else continue;

}
}

最佳答案

要查找空指针异常,请使用调试器。您的变量之一为空。

但是一旦修复了这个问题,您就无法在遍历列表时修改它。您提供的代码中最简单的解决方案是更改您的 foreach循环到 for循环。

来自 foreach 的 MSDN 文档:

The foreach statement repeats a group of embedded statements for each element in an array or an object collection. The foreach statement is used to iterate through the collection to get the desired information, but should not be used to change the contents of the collection to avoid unpredictable side effects.

关于C# 在处理列表时给出 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6235157/

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