C# - 与拳击/拆箱/整数类型转换的问题。我不明白 [英] C# - Issues with boxing / unboxing / typecasting ints. I don't understand

查看:106
本文介绍了C# - 与拳击/拆箱/整数类型转换的问题。我不明白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很难理解这一点。请看下面的例子:

I'm having a hard time understanding this. Consider the following example:

protected void Page_Load(object sender, EventArgs e)
{
    // No surprise that this works
    Int16 firstTest = Convert.ToInt16(0);
    int firstTest2 = (int)firstTest;

    // This also works
    object secondTest = 0;
    int secondTest2 = (int)secondTest;

    // But this fails!
    object thirdTest = Convert.ToInt16(0);
    int thirdtest2 = (int)thirdTest;  // It blows up on this line.
}

这是我在运行时获取特定的错误是指定转换无效。如果我快速监视(INT)thirdTest 在Visual Studio中,我得到的值不能拆箱 thirdTest'作为'廉政'

The specific error that I get at runtime is Specified cast is not valid. If I QuickWatch (int)thirdTest in Visual Studio, I get a value of Cannot unbox 'thirdTest' as a 'int'.

到底是什么怎么回事?

推荐答案

拆箱检查作为文档中解释的确切类型

拆箱是从object类型的值
型或从接口类型为显式转换实现
接口值类型。一个拆箱操作包括:

Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface. An unboxing operation consists of:


  • 检查对象实例,以确保它是$ B $的装箱值b给定值的类型。

  • Checking the object instance to make sure that it is a boxed value of the given value type.

复制从实例中的值转换成数值型变量。

Copying the value from the instance into the value-type variable.

正如你所看到的第一个步骤是检查对象实例的目标类型相匹配。

As you can see the first step is to check that the object instance matches the target type.

另外从文档报价:

有关值类型的拆箱在运行时取得成功,该项目是
拆箱必须是以前通过拳击该值类型的实例创建
对象的引用。试图拆箱空
会导致一个NullReferenceException。试图拆箱到
不兼容的值类型的引用导致一个InvalidCastException。

For the unboxing of value types to succeed at run time, the item being unboxed must be a reference to an object that was previously created by boxing an instance of that value type. Attempting to unbox null causes a NullReferenceException. Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.

因此​​,要解决这个错误请确保类型尝试拆箱之前匹配:

So to fix this error make sure that the type matches before attempting to unbox:

object thirdTest = Convert.ToInt16(0);
short thirdtest2 = (short)thirdTest;  

这篇关于C# - 与拳击/拆箱/整数类型转换的问题。我不明白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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