I know that when a NullReferenceException
gets thrown, the error message states:
Object reference not set to an instance of an object.
And I realize this message is thrown when I attempt to dereference a null
object reference.
The error message implies that there could be a reason for a NullReferenceException
besides an object reference being null
(perhaps a bad memory address or something similar). Is this the case?
Edit: I'm more concerned with the reasons aNullReferenceException
could be thrown than the wording of the err开发者_开发百科or message. The wording of the error message is just what prompted the question.
I suspect it's trying to be language-neutral. A Visual Basic programmer is used to "nothing" instead of "null", for example. Obviously the type name isn't language neutral, but at least if the message is, that's a start.
I don't know that you'd get this if somehow you tried to dereference a "bad" memory address... at that point there's a far worse CLR error involved.
Another possibility is that it's trying to avoid stating that you've explicitly set the value of the reference to null - it could be just the default value of a reference type variable, for example.
Saying the reference is set to null doesn't say a whole lot about what needs to be done. In their attempt to be more "helpful", they are telling you what needs to happen: The object reference needs to be set to an instance of an object.
I don't really read that as implying there could be other reasons besides a reference being null. If it was left uninitialized, it causes a compile error. The bottom line is that the reference doesn't refer to anything at the time you attempted to use it.
When an object is declared like so:
MyClass MyObject;
it is defined as an object reference. However, because it is null (and has not been instantiated), it is not set to an instance of an object. If we add:
MyObject = new MyClass();
then the reference has been set to a new instance of the object.
If we later set it to null:
MyObject = null;
Then it is again in the null state. Therefore, the exception message covers both cases (not instantiated or explicitly set to null).
It's part of the Common Language Specification. Take a look at the difference between a static method and an instance method.
A static method belongs to the Type, and as such does not require an instance. If you look at the IL byte code, static methods are referred to as "call".
However, a non-static method is by definition an instance method and requires an instance. The IL instruction is "callvirt". The key difference between "call" and "callvirt" is that "callvirt" checks to see that the target to invoke the method against is not null.
精彩评论