问题
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