Getting the variable name for NullReferenceException

大兔子大兔子 提交于 2019-11-28 01:10:15

问题


Stack traces for NullReferenceException is very uninformative, they just include the method name and the call stack. Any variable in a method can be null and it's hard to debug when the bug isn't reproducible on the dev machine.

Do you know a way to get more info on that error, getting the variable name perhaps? Or do you have better ways to debug it?


回答1:


Keeping track of that name is not always possible (it could be an expression).
And where it is possible it would incur unacceptable overhead. Consider that the runtime would have to track almost all reference variables, that would be costly and prohibit all sorts of optimizations.

Also see my answer on Inspect the managed stack and the Blog post it refers to.

The simple solution is to build in more consistent null checking in your own code:

void Foo(Bar b)
{
   if (b == null) throw new ArgumentNullException(nameof(b));

   ...
}


来源:https://stackoverflow.com/questions/34442419/getting-the-variable-name-for-nullreferenceexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!