在不可能的情况下获取NullReferenceException(检查null时)

mut*_*tex 6 c# nullreferenceexception

我在我的一个方法的开头有一个非常简单的检查,如下所示:

public void MyMethod(MyClass thing)
{
    if(thing == null)
        throw new ArgumentNullException("thing");

    //Do other stufff....
}
Run Code Online (Sandbox Code Playgroud)

但我得到的堆栈跟踪(来自生产环境中的Elmah)似乎表明"if(thing == null)"行正在抛出NullReferenceException.堆栈跟踪的前两行是这样的:

System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at MyLibrary.BL.AnotherClass.MyMethod(MyClass thing) in C:\Development\MyProject\trunk\MyLibrary.BL\AnotherClass.cs:line 100
Run Code Online (Sandbox Code Playgroud)

MyClass是一个相当简单的类,没有运算符重载或类似的东西,所以我有点难以理解抛出NullReferenceException的内容!

任何人都可以提出可能导致此问题的情景吗?

编辑:我怀疑"事物"可能是null,但我真的希望ArgumentNullException不是NullReferenceException - 这基本上是这个问题的关键.可能是框架或Elmah正在改变或错误报告异常的某些东西 - 或者是二进制文件以某种方式过时的唯一解释?

Joh*_*ers 4

if (thing == null)抛出是不可能的NullReferenceException

这意味着正在发生其他事情。是时候开始运用你的想象力,并下定决心,忽略由此if引起的问题的可能性。

  • 这个故事的寓意是:如果您在执行代码时遇到“NullReferenceException”,并且源代码表明不可能在堆栈跟踪中指示的行中获得“NullReferenceException”,那么这是因为您的源代码确实与您正在执行的二进制代码不匹配。 (2认同)