我会通过一些code和碰到这样一个场景,我的组合框还没有被初始化。这是在.NET 2.0和以下code,this.cbRegion.SelectedValue为空。
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.
int id = (int)this.cbRegion.SelectedValue;
这code扔了一个空引用异常,而不是一个无效的转换异常。我想知道是否有人知道为什么它会抛出一个无效的转换一个空引用异常呢?
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?
它做拳击并拆箱。它试图拉一个int开箱(拆箱),但对象是空的,所以你得到一个空引用异常之前,它曾经得到施展的变化。
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.