问题描述
在我看来,我的大量调试时间都花在了追踪复杂语句中的空引用异常上.例如:
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()
为什么,当我得到 NullReferenceException 时,我可以得到堆栈跟踪中的行号,而不是等于 null 的对象的名称.换句话说,为什么:
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.
而不是
_GamesToOpen is not set to an instance of an object.
或
Anonymous object returned by _GamesToOpen.GetIterator() is null.
或
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.
实际上,您示例中的变量是一个表达式.表达式并不总是简单的变量.在运行时,将评估表达式并在结果对象上调用方法.如果该表达式的值为 null
,则运行时将抛出 NullReferenceException
.假设如下:
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()
如果GetNullValue()
方法返回null
,运行时应该返回什么错误信息?
What error message should the runtime return if the GetNullValue()
method returns null
?
这篇关于为什么空引用异常不能命名具有空引用的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!