不设置到object.Why的实例对象引用不.NET显示哪些对象`null`? [英] Object reference not set to an instance of an object.Why doesn't .NET show which object is `null`?
问题描述
对此.NET未处理的异常信息:
Regarding this .NET unhandled exception message:
对象引用不设置到对象的实例
Object reference not set to an instance of an object.
为什么不.NET显示哪些对象是空
?
Why doesn't .NET show which object is null
?
我知道我可以检查空
并解决错误。然而,为什么不.NET帮助指出哪个对象具有空引用和表达触发了的NullReferenceException
?
I know that I can check for null
and resolve the error. However, why doesn't .NET help pointing out which object has a null-reference and which expression triggered the NullReferenceException
?
推荐答案
考虑以下代码:
String s = null;
Console.WriteLine(s.Length);
这将在第二抛出一个的NullReferenceException
行,你想知道为什么.NET不告诉你,这是取值
这是空时抛出异常。
This will throw a NullReferenceException
in the second line and you want to know why .NET doesn't tell you that it was s
that was null when the exception was thrown.
要明白你为什么没有得到资料片,你应该记住,这是不是C#源即执行,而是IL:
To understand why you don't get that piece of information you should remember that it is not C# source that executes but rather IL:
IL_0001: ldnull
IL_0002: stloc.0 // s
IL_0003: ldloc.0 // s
IL_0004: callvirt System.String.get_Length
IL_0009: call System.Console.WriteLine
这是抛出 callvirt
操作码的NullReferenceException
,它不会当计算堆栈上的第一个参数为空引用(即使用加载一个 ldloc.0
)。
It is the callvirt
opcode that throws the NullReferenceException
and it does that when the first argument on the evaluation stack is a null reference (the one that was loaded using ldloc.0
).
如果.NET应该能够告诉大家,这是取值
这是一个空引用应该以某种方式跟踪计算堆栈上的第一个参数起源形式取值
。在这种情况下,我们很容易地看到,这是一个为空但如果该值从另一个函数调用的返回值,而不是存储在任何变量取值
?无论如何,这种信息是不是你想跟踪虚拟机像.NET虚拟机的东西。
If .NET should be able to tell that it was s
that was a null reference it should in some way track that the first argument on the evaluation stack originated form s
. In this case it is easy for us to see that it is s
that was null but what if the value was a return value from another function call and not stored in any variable? Anyway, this kind of information is not what you want to keep track of in a virtual machine like the .NET virtual machine.
要避免这个问题,我建议你在所有的公共方法调用执行参数空检查(当然,除非你允许空引用):
To avoid this problem I suggest that you perform argument null checking in all public method calls (unless of course you allow the null reference):
public void Foo(String s) {
if (s == null)
throw new ArgumentNullException("s");
Console.WriteLine(s.Length);
}
如果null被传递给方法你可以精确地描述了什么异常问题是(即取值
为空)。
If null is passed to the method you get an exception that precisely describes what the problem is (that s
is null).
这篇关于不设置到object.Why的实例对象引用不.NET显示哪些对象`null`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!