C# - 装箱/拆箱/类型转换整数的问题。我不明白

标签 c# c#-4.0 casting boxing unboxing

我很难理解这一点。考虑以下示例:

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.
}

我在运行时得到的特定错误是 Specified cast is not valid. 如果我在 Visual Studio 中使用 QuickWatch (int)thirdTest,我得到的值是 无法将“thirdTest”拆箱为“int”

这到底是怎么回事?

最佳答案

拆箱检查确切类型,如 documentation 中所述.

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:

  • 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.

如您所见,第一步是检查对象实例是否与目标类型匹配。

另引自文档:

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.

因此,要修复此错误,请确保在尝试拆箱之前类型匹配:

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

关于C# - 装箱/拆箱/类型转换整数的问题。我不明白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8771476/

相关文章:

c# - 使用 BouncyCaSTLe 加密私钥

c#-4.0 - 如何用表达式树动态创建方法和属性?

asp.net - 使用 oauth2 进行身份验证以转到网络研讨会

c++ - 如何从 unsigned long 转换为 void*?

typescript :如何将字符串转换为类型

c# - 如何通过分解 y 轴来减小 mschart 的高度

c# - Silverlight 与 MVVM : How to access Event of the ViewModel from the View?

c# - C# 中需要可选的 VB 参数

c# - 如何使用 OpenCVSharp 将 Mat 转换为 Bitmap?

c++ - 这个 Actor 分配了什么? C风格选角