C# - Issues with boxing / unboxing / typecasting ints. I don't understand

前端 未结 3 672
礼貌的吻别
礼貌的吻别 2020-12-02 00:28

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

protected void Page_Load(object sender, EventArgs e)
{
    // No surprise that t         


        
3条回答
  •  爱一瞬间的悲伤
    2020-12-02 01:03

    Unboxing checks the exact type as explained in the 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.

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

    Also quote from the documentation:

    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;  
    

提交回复
热议问题