【问题标题】:Object reference not set to an instance of an object, but I see nothing illegal [duplicate]对象引用未设置为对象的实例,但我没有看到任何非法 [重复]
【发布时间】:2017-05-21 01:33:27
【问题描述】:

这可能会被标记为重复或关闭,但我需要问一下。这里有什么不合法的?

private void btnFind_Click(object sender, EventArgs e)
{
    connection.Open();
    OleDbCommand command1 = new OleDbCommand();
    command1.Connection = connection;
    command1.CommandText = "select antonym from antonymsdb where word ='" + txtWord.Text + "'";
    string antonymdoc = command1.ExecuteScalar().ToString();
    lblAntonym.Text = antonymdoc;

    OleDbCommand command2 = new OleDbCommand();
    command2.Connection = connection;
    command2.CommandText = "select word from antonymsdb where antonym = '" + txtWord.Text + "'";
    string antonymdocx = command2.ExecuteScalar().ToString();
    lblAntonym.Text = antonymdocx;
    connection.Close();
}

我正在尝试读取 wordantonym 两列并返回同一行的单词,只是不同的列。它一直显示错误,我尝试搜索互联网,但没有发现任何帮助...

【问题讨论】:

  • It keeps showing error 错误文本是什么?
  • 使用调试器
  • 我不知道为什么这是重复的。问题不在于 NullReferenceException 是什么。问题是为什么这段代码会抛出一个。尽管如前所述,这是在调试器中更容易找到的东西。除非它是生产代码并且您所拥有的只是引发异常的方法。然后我们必须阅读代码并播放“find the null”。
  • @ScottHannen 它是“如何修复它”部分的副本。每次修复 NRE 的方式都是相同的,并且它不会为站点增加一点价值来不断重复“分解链式调用并找到为空的特定部分,然后在程序中回溯并找出原因变量为空”。现在,如果问题是“我发现 command1.ExecuteScalar() 将返回 null 导致 .ToString() 抛出 NRE,我不明白为什么我没有从 ExecuteScalar() 获得值”这不会是一个重复的问题。

标签: c# visual-studio ms-access visual-studio-2013


【解决方案1】:

这是嫌疑人:

string antonymdoc = command1.ExecuteScalar().ToString();

如果查询没有返回记录,则ExecuteScalar 返回 null。如果你尝试在 null 上调用 .ToString(),你会得到一个 NullReferenceException

通常我会先检查结果是否为空,以便知道它是否返回了结果。

如果你只是想在没有结果的时候得到一个空字符串,你可以这样做

string antonymdoc = command1.ExecuteScalar()?.ToString() ?? string.Empty;

这是的简写

var output = command1.ExecuteScalar();
string antonymdoc = output != null ? output.ToString() : string.Empty;

这是

的简写
var output = command1.ExecuteScalar();
string antonymdoc;
if(output!=null)
{
    antonymdoc - output.ToString(); 
}
else
{
    antonymdoc = string.Empty;
}

【讨论】:

    猜你喜欢
    • 2010-09-12
    • 1970-01-01
    • 2017-04-14
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2013-11-17
    相关资源
    最近更新 更多