B. *_*non 0 c# .net-1.1 struct exception nullreferenceexception
有一个结构:
public struct ReturnedCommands
{
public string key;
public string command;
};
Run Code Online (Sandbox Code Playgroud)
......和一个变量:
public static ReturnedCommands returnedCommands;
Run Code Online (Sandbox Code Playgroud)
...并且发生Null Reference Exception,返回值"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
Run Code Online (Sandbox Code Playgroud)
当NRE发生时,它显示"异常:空引用异常达到debug int 3".因此,它必须在引用returnedCommands.command时发生爆炸,但是怎么可能,因为returnedCommands.command只是一个字符串?首先验证它不为空("if(returnedCommands.command!= null)"行)应该是安全的,这样测试就不会有问题; 如果它通过了那个测试,它只是一个字符串连接操作,那怎么会导致一个NRE呢?
如果PendingCommands.SiteFetchSiteNumber为null(因此sNum为null),那么当您调用sNum.Trim()时,这将导致空引用异常
此外,如果您显示完整的堆栈跟踪,它应该为您提供发生错误的确切行号,这比使用增量值来计算它要简单得多.
| 归档时间: |
|
| 查看次数: |
156 次 |
| 最近记录: |