Why can#39;t a null-reference exception name the object that has a null reference?(为什么空引用异常不能命名具有空引用的对象?)
问题描述
在我看来,我的大量调试时间都花在了追踪复杂语句中的空引用异常上.例如:
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
?
这篇关于为什么空引用异常不能命名具有空引用的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么空引用异常不能命名具有空引用的对象?
基础教程推荐
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01