有一个结构:
public struct ReturnedCommands
{
public string key;
public string command;
};
...和一个变量:
public static ReturnedCommands returnedCommands;
...并且发生空引用异常,返回值“3”:
public bool PendingCommandsExecute_QUERY()
{
int i = 0;
try
{
i = 1;
cmdResults b = cmdResults.cmdFail;
bool retVal = false;
string command = "QUERY";
if (returnedCommands.key != command)
return false;
HashResultsAdd(command, "Started");
i = 2;
HashStatus.Clear();
string sNum = PendingCommands.SiteFetchSiteNumber;
i = 3; // <-- last one reached (debug int displayed in NRE)
string s = string.Empty;
if (returnedCommands.command != null)
{
s = command + "|" + sNum.Trim() + "|t_inv|SELECT|" + returnedCommands.command;
}
i = 4;
HashStatusAdd(command, s);
. . .
}
catch( Exception ex )
{
MessageBox.Show(ex.Message + " reached debug int " + i.ToString());
}
return true;
} // PendingCommandsExecute_QUERY
当 NRE 发生时,它显示“异常:空引用异常达到调试 int 3”。所以,它在引用returnedCommands.command 时一定是内爆,但怎么可能呢,因为returnedCommands.command 只是一个字符串?首先验证它不为空(“if (returnedCommands.command != null)”行)应该是安全的,这样测试就不应该有问题;如果它通过了该测试,它只是一个字符串连接操作,那怎么会导致 NRE 呢?