奇怪的铸造行为。不能施放对象(INT)长 [英] Strange casting behaviour. Cannot cast object (int) to long
问题描述
我有以下代码:
int intNumber1 = 100;
object intNumber2 = 100;
bool areNumberOfTheSameType = intNumber1.GetType() == intNumber2.GetType(); // TRUE
bool areEqual = intNumber1.Equals(intNumber2); // TRUE
long longNumber1 = (long) intNumber1; // OK
long longNumber2 = (long) intNumber2; // InvalidCastException. Why?
为什么没有第二科协工作?我意识到这可能是因为对象没有明确的强制转换为长,但如果我们看看它的类型上运行时,它是 System.Int32
。
如果我用或
,它的工作原理。动态
而不是<$ C> $ C>对象
If I use var
or dynamic
instead of object
, it works.
有什么想法?
推荐答案
从 INT
投放到长
被解释为两种类型之间的转换。
Cast from int
to long
is interpreted as conversion between the two types.
从对象
投放到 INT
被解释为拆箱装箱 INT
。
Cast from object
to int
is interpreted as unboxing a boxed int
.
这是相同的语法,但它说,两个不同的东西。
It is the same syntax, but it says two different things.
在工作情况下( INT
→长
,对象
(盒装 INT
)→ INT
),编译器确切地知道什么样的代码来制作。如果盒装 INT
→长
是工作,编译器会以某种方式弄清楚要使用的转换,但它没有足够的信息来做到这一点。
In the working cases (int
→long
, object
(boxed int
)→int
), the compiler knows exactly what code to produce. If boxed int
→long
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.
又见的从埃里克利珀这个博客帖子。
这篇关于奇怪的铸造行为。不能施放对象(INT)长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!