NullReferenceException was caught...?

本文关键字:caught was NullReferenceException | 更新日期: 2023-09-27 18:23:36

运行foreach循环后。我在第二个项上得到了NullReferenceException,因为查询结果为null。但我在同一个查询中有更多的项要使用,并在richTextBox1上获得结果。因此,如果有任何空结果,我可以继续foreach循环吗。

foreach (string Items in listBox4.Items)
{
    using (OracleCommand crtCommand = new OracleCommand("select REGEXP_REPLACE(dbms_metadata.get_ddl('TABLE','" + Items + "'),('" + txtSrcUserID.Text + "...'),'', 1, 0, 'i') from dual", conn1))                           
    {
        richTextBox1.AppendText(Environment.NewLine);
        richTextBox1.AppendText(crtCommand.ExecuteScalar().ToString() + ";");
        richTextBox1.AppendText(Environment.NewLine);
    }                                                      
}

NullReferenceException was caught...?

这是危险的编程。你真的应该检查一下null。假设你的循环会变大。。我会包含一个continue,让它更明显地表明您为可读性所做的事情。如果您不需要continue,请省略它。

var result = crtCommand.ExecuteScalar();
if (result != null) {
    richTextBox1.AppendText(Environment.NewLine);
    richTextBox1.AppendText(result.ToString() + ";");
    richTextBox1.AppendText(Environment.NewLine);
}
else {
    continue;
}
// any other code here.

crtCommand.ExecuteScalar().ToString()更改为(crtCommand.ExecuteScalar() ?? string.Empty).ToString()。这在逻辑上等同于:

  object dbResult = crtCommand.ExecuteScalar();
  if(dbResult == null) 
  {
     richTextBox1.AppendText(";");
  }
  else
  {
     richTextBox1.AppendText(dbResult.ToString() + ";");
  }

如果您想完全忽略null结果,而不是将其视为空字符串,请使用@SimonWhitehead的代码