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

后端 未结 5 1921
陌清茗
陌清茗 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:11

    (Caution: Guess)

    Int32 has a conversion operator to Int64 which is what gets invoked when you do the first cast. Object doesn't, so your second cast is trying to cast an object to another type which isn't a supertype (Int64 doesn't inherit Int32).

    The reason why it works with var is obvious – the compiler just saves you from typing int in that case. With dynamic the runtime does all necessary checks for what needs to be done while normally the compiler would just insert either the cast or invoke the conversion operator.

提交回复
热议问题