Strange casting behaviour. Cannot cast object (int) to long

后端 未结 5 1944
陌清茗
陌清茗 2020-12-29 01:16

I have the following code:

int intNumber1 = 100;
object intNumber2 = 100;
bool areNumberOfTheSameType = intNumber1.GetType() == intNumber2.GetType(); // TRUE         


        
5条回答
  •  清歌不尽
    2020-12-29 02:17

    Cast from int to long is interpreted as conversion between the two types.

    Cast from object to int is interpreted as unboxing a boxed int.

    It is the same syntax, but it says two different things.

    In the working cases (intlong, object (boxed int)→int), the compiler knows exactly what code to produce. If boxed intlong was to work, the compiler would have to somehow figure out which conversion to use, but it doesn't have enough information to do it.

    See also this blog post from Eric Lippert.

提交回复
热议问题