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

后端 未结 5 1891
陌清茗
陌清茗 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 01:59

    That it doesn't work due to being two different types of casts (one converting, the other unboxing) has already been stated in answers here. What might be a useful addition, is that Convert.ToInt64() will convert anything that is either a built-in type that can be converted to long, or a type of a class that implements IConvertible.ToInt64(), into a long. In other words, if you want to be able to cast an object that contains an integer (of whatever size) to long, Convert.ToInt64() is the way to go. It is more expensive, but what you are trying to do is more expensive that casting, and the difference is negliable (just big enough to be wasteful in cases where you know the object must be a boxed long).

提交回复
热议问题