为什么不能一个空引用异常的名字,有一个空引用的对象吗? [英] Why can't a null-reference exception name the object that has a null reference?

查看:257
本文介绍了为什么不能一个空引用异常的名字,有一个空引用的对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,很多我的调试时间都花在追逐下来复杂的语句空引用异常。例如:

 每场比赛作为IHomeGame在_GamesToOpen.GetIterator()
 

为什么,当我得到一个NullReferenceException,我可以得到的堆栈跟踪的行号,但不等于空的对象的名称。换句话说,原因如下:

 对象引用不设置到对象的实例。
 

而不是

  _GamesToOpen未设置为一个对象的实例。
 

通过_GamesToOpen.GetIterator()返回

 匿名对象为null。
 

 游戏被设置为null。
 

这是严格意义上的设计选择,为了保护的code的匿名性,还是有充分的理由在编译器设计不包括在调试时异常信息?

解决方案

例外的是运行时的事情,变量是编译时的事情。

其实,在您的示例中的变量是的的前pression 的。防爆pressions并不总是简单的变量。在运行时,EX pression将进行评估,该方法将被调用生成的对象。如果说前pression值为,运行时将抛出一个的NullReferenceException 。假设如下:

 暗淡了作为新的MyObject
昏暗b以字符串= MyObject.GetNullValue()的ToString()
 

什么错误消息应该在运行时返回,如果 GetNullValue()方法的返回值

It seems to me that a lot of my debugging time is spent chasing down null-reference exceptions in complex statements. For instance:

For Each game As IHomeGame in _GamesToOpen.GetIterator()

Why, when I get a NullReferenceException, can I get the line number in the stack trace, but not the name of the object that equals null. In other words, why:

Object reference not set to an instance of an object.

instead of

_GamesToOpen is not set to an instance of an object.

or

Anonymous object returned by _GamesToOpen.GetIterator() is null.

or

game was set to null.

Is this strictly a design choice, meant to protect the anonymity of the code or is there a compelling reason in compiler design not to include this information in the debug-time exception?

解决方案

Exceptions are runtime things, variables are compile time things.

In fact, the variable in your example is an expression. Expressions are not always simple variables. At runtime, the expression will be evaluated and the method will be called on the resulting object. If the value of that expression is null, the runtime will throw a NullReferenceException. Assume the following:

Dim a as New MyObject
Dim b as String = MyObject.GetNullValue().ToString()

What error message should the runtime return if the GetNullValue() method returns null?

这篇关于为什么不能一个空引用异常的名字,有一个空引用的对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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