0

有一个结构:

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 呢?

4

2 回答 2

5

如果 PendingCommands.SiteFetchSiteNumber 为空(因此 sNum 为空),那么当您调用 sNum.Trim() 时这将导致空引用异常

此外,如果您显示完整的堆栈跟踪,它应该为您提供发生错误的确切行号,这比使用增量值来调试要简单得多。

于 2013-06-10T15:52:06.763 回答
1

这很可能是对公共静态成员的多线程访问的缺失检查。

public static ReturnedCommands returnedCommands;

我看不到你到底想在那里实现什么,但我认为你正在审查架构,因为当其他线程可以访问该成员并用 null 覆盖它时,它很可能会失败。

可能您可以为您的命令使用队列。

于 2013-06-10T16:14:38.060 回答