为什么空引用异常不能命名具有空引用的对象?

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?

这篇关于为什么空引用异常不能命名具有空引用的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
quot;Overflowquot; compiler error with -9223372036854775808L(编译器错误-9223372036854775808L(Q;溢出Q))
Visual Studio 2010 ReportViewer Assembly References(Visual Studio 2010 ReportViewer程序集引用)
Weird behaviour when I open a reportviewer in WPF(在WPF中打开报表查看器时出现奇怪的行为)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)