为什么在.net 2.0中的一个原始类型(ie: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?

查看:193
本文介绍了为什么在.net 2.0中的一个原始类型(ie:int)中引入一个null,抛出一个空引用异常而不是一个无效的转换异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览一些代码,发现我的组合框尚未初始化的情况。这是在.NET 2.0和在下面的代码,this.cbRegion.SelectedValue为null。

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;

此代码引发了一个空引用异常,而不是无效的投射异常。我想知道是否有人知道为什么它会抛出一个空引用异常而不是一个无效的转换?

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的框(unbox),但对象是null,所以你得到一个null引用异常之前,它得到的更改转换。

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.

这篇关于为什么在.net 2.0中的一个原始类型(ie:int)中引入一个null,抛出一个空引用异常而不是一个无效的转换异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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