为什么铸造空到原语(即:INT)在.NET 2.0抛出空裁判例外,而不是一个无效的转换异常? [英] 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?

查看:159
本文介绍了为什么铸造空到原语(即:INT)在.NET 2.0抛出空裁判例外,而不是一个无效的转换异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会通过一些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.

这篇关于为什么铸造空到原语(即:INT)在.NET 2.0抛出空裁判例外,而不是一个无效的转换异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆