获取NullReferenceException的变量名 [英] Getting the variable name for NullReferenceException

查看:90
本文介绍了获取NullReferenceException的变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

NullReferenceException 的堆栈跟踪非常无用,它们仅包含方法名称和调用堆栈。方法中的任何变量都可以为null,并且当在开发机器上无法再现该错误时,很难调试。

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?

推荐答案

并非总是可以跟踪该名称的(它可以是一个表达式)。

并且在可能的情况下会产生不可接受的开销。考虑到运行时将不得不跟踪几乎所有的参考变量,这将是昂贵的,并且会禁止各种优化。

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.

简单的解决方案是在自己的代码中构建更一致的null检查:

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));

   ...
}

这篇关于获取NullReferenceException的变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆