C#在处理列表时给出NullReferenceException

问题描述

| 以下代码在处理时给出了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;

                }
            }
    

解决方法

        要查找空指针异常,请使用调试器。您的变量之一为null。 但是,一旦修复该问题,就无法在迭代列表时修改列表。您提供的代码中最简单的解决方案是将
foreach
循环更改为
for
循环。 从
foreach
的MSDN文档中:   foreach语句为数组或对象集合中的每个元素重复一组嵌入式语句。 foreach语句用于遍历集合以获取所需的信息,但不应用于更改集合的内容,以避免不可预期的副作用。     ,        您可能有
null
Value
,因此
ToString()
失败了。     ,        一些可能性:
row.Cells[0]
为空
row.Cells[1]
为空
row.Cells[0].Value
为空
row.Cells[1].Value
为空     ,        您不能从要迭代的集合中删除元素。解决方案是将要删除的元素列表存储在另一个List中,然后在另一个迭代中将其删除。以下是一个解决方案。
    //New list that will contain the Objects to be deleted later on.
    List<DataGridView> listToDelete = new List<DataGridView>();

    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())
                {
                    listToDelete.Add(row);
                }
            }
        }
    }

    foreach (DataGridView d in listToDelete) {
        a.Remove(d);
    }
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...