作为开发人员,我们经常遇到这种异常:NullReferenceException
众所周知的错误消息:
你调用的对象是空的
.NET 框架不可能返回更有意义的东西吗?
例如:
名为 Y 的 X 类型对象未设置为对象的实例
作为开发人员,我们经常遇到这种异常:NullReferenceException
众所周知的错误消息:
你调用的对象是空的
.NET 框架不可能返回更有意义的东西吗?
例如:
名为 Y 的 X 类型对象未设置为对象的实例
An object doesn't have a name - so how can it tell you the name? The null reference may have been loaded from a variable - or it might have been returned by a method, property etc.
The JIT could probably look at the stack information to work out what the declared reference type was, but I'm not sure how often this would help - and doubtless it would slow things down.
I can't say I've ever found this to be a huge burden when it comes to debugging - if there are lots of things which can be null on a single line, that usually suggests that it's worth splitting them up more.
对我来说,这似乎纯粹是一个偏好问题。如果它让你烦恼那么多,你总是可以继承NullReferenceException
并更改消息。:)
它归结为创建消息时可用的信息量。在不手动传递一些额外信息的情况下,简单地确定其中为 null 的字段的名称NullReferenceException
将需要反射(可能相当多),这是一个相当繁重的操作。例如ArgumentNullException
,为了抛出一个消息指示有问题的参数名称,您必须在调用它时传入一个字符串:throw new ArgumentNullException("param1")
。
异常消息中的详细程度完全取决于定义它的程序员,但在引发异常时避免做任何系统密集的事情是谨慎的。
Because its the most generic way of saying that.