NullReferenceException 位置信息?

NullReferenceException location information?

我有一个应用程序(已发布)和一个很少为用户弹出的 NullReferenceException,但我想处理它。我查看了其中的堆栈和方法,但找不到它会出现的具体位置(这是一个相当大的 method/algorithm)。现在我将只用 try/catch 围绕调用本身,但如果我能弄清楚情况,我想更好地处理它。
问题是,据我所知,NRE 没有提供关于代码中具体是什么导致它的线索。有没有办法甚至获取行号或任何其他可能暗示原因的信息?

几点提示:

  1. 如果您将符号文件 (.pdb) 与 executable/dll 文件一起部署,那么您获得的堆栈跟踪将包含行号。
  2. 它也有助于将您的方法分解成更小的部分,这样您的堆栈跟踪可以让您更好地了解错误发生时您所在的位置。
  3. 您可以通过检查其输入是否存在空值或其他无效值来开始每个方法,这样您就可以快速失败并提供有意义的消息。

    private void DoSomething(int thingId, string value)
    {
        if(thingId <= 0) throw new ArgumentOutOfRangeException("thingId", thingId);
        if(value == null) throw new ArgumentNullException("value");
        ...
    }
    
  4. 您可以用异常包装器包围每个方法,以便在堆栈跟踪的每个级别提供更多信息。

    private void DoSomething(int thingId, string value)
    {
        try
        {
            ...
        }
        catch (Exception e)
        {
            throw new Exception("Failed to Do Something with arguments " +
                new {thingId, value},
                e); // remember to include the original exception as an inner exception
        }
    }