[英]Why does casting a null to a primitive(ie: int) in .net 2.0 throw a null ref exception and not a invalid cast exception?
I was going through some code and came across a scenario where my combobox has not been initialized yet. 我正在浏览一些代码并遇到了我的组合框尚未初始化的情况。 This is in .NET 2.0 and in the following code, this.cbRegion.SelectedValue is null.
这是在.NET 2.0中,在下面的代码中,this.cbRegion.SelectedValue为null。
int id = (int)this.cbRegion.SelectedValue;
This code threw a null reference exception instead of an invalid cast exception. 此代码抛出了空引用异常,而不是无效的强制转换异常。 I was wondering if anyone knew why it would throw a null reference exception instead of a invalid cast?
我想知道是否有人知道为什么它会抛出空引用异常而不是无效的强制转换?
If you compile 如果你编译
object o = null;
int a = (int)o;
and look at the MSIL code, you'll see something like 看看MSIL代码,你会看到类似的东西
ldnull
...
unbox.any int32
Now the behavior for unbox.any is specified as follows: 现在,unbox.any的行为指定如下:
InvalidCastException is thrown if obj is not a boxed type.
如果obj不是盒装类型,则抛出InvalidCastException。
NullReferenceException is thrown if obj is a null reference.
如果obj是空引用,则抛出NullReferenceException。
This is what you see in your code. 这是您在代码中看到的内容。
It's attempting to read the object before it casts it. 它试图在它投射之前读取对象。 Hence you're getting the null exception instead of a cast exception.
因此,您将获得null异常而不是强制转换异常。
The exception is on the Selected Value which is null. “选定值”上的例外是null。 It's never even getting to the cast.
它甚至都没有进入演员表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.