Confused by Boxing. Casting -1 to Int64 throws InvalidCastException

前端 未结 1 1177
我寻月下人不归
我寻月下人不归 2021-02-08 12:40

Ok I must be overlooking something extremely simple but I am lost.

Given this

object val = -1;
var foo = (Int32)(val);
var bar = (Int64)(val);


        
相关标签:
1条回答
  • 2021-02-08 13:20

    This is because you can't unbox and perform a conversion in a single operation. You must unbox the Int32 value into an Int32, and then subsequently convert its type.

    Because of that, this requires the object to be unboxed, then converted to Int64:

    object val = -1;
    int foo = (Int32)val;
    Int64 bar = (Int64)(Int32)val;
    

    Eric Lippert covered this in detail on his blog post titled Representation and Identity.

    0 讨论(0)
提交回复
热议问题