简体   繁体   English

为什么在.net 2.0中向原语(即:int)转换null会抛出空引用异常而不是无效的转换异常?

[英]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? 我想知道是否有人知道为什么它会抛出空引用异常而不是无效的强制转换?

It has to do with Boxing and unboxing. 它与拳击和拆箱有关。 It is trying to pull an int out of the box (unbox), but the object is null, so you get a null reference exception before it ever gets the change to cast. 它试图从框中取出一个int(unbox),但该对象为null,因此在获得转换更改之前,您将获得一个空引用异常。

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.

相关问题 为什么将 int 转换为无效的枚举值不会引发异常? - Why does casting int to invalid enum value NOT throw exception? .Net 2+:为什么 if( 1 == null ) 不再引发编译器异常? - .Net 2+: why does if( 1 == null ) no longer throw a compiler exception? 为什么Silverlight View不会引发null异常? - Why does Silverlight View not throw a null exception? 为什么这会引发空引用异常? - Why does this throw a null reference exception? Json.net linq to json将null转换为JObject抛出异常 - Json.net linq to json cast null to JObject throw exception 为什么我的代码会引发无效的强制转换异常? (C#)? - Why does my code throw an Invalid Cast Exception? (C#)? 强制转换为无效的枚举值Enum.ToObject不会引发异常,将Enum设置为int - Casting to invalid enum value, Enum.ToObject, does not throw exception, sets Enum to int 为什么对 DataRow 空值的这种取消引用不会引发异常? - Why does this dereference of a DataRow null value not throw an exception? 为什么会话对象抛出空引用异常? - Why does session object throw a null reference exception? 为什么这个嵌套对象初始化器抛出一个空引用异常? - Why does this nested object initializer throw a null reference exception?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM