拳击困惑。铸造-1的Int64抛出InvalidCastException的拳击、抛出、困惑、InvalidCastException

2023-09-03 12:47:51 作者:南笙一梦

好吧,我必须忽视的东西非常简单,但我迷路了。

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

鉴于这种

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

演员到Int64的罚球和InvalidCastException的。

The cast to Int64 throws and InvalidCastException.

我承认这是关系到拳击有些陌生,但我不明白的道理。

I recognize this is related to some strangeness with boxing but I don't understand the reasoning.

据我了解VAL是盒装作为的Int32的第一行。

From what I understand val is boxed as Int32 on the first line.

然后,当我尝试转换的东西比的Int32 InvalidCastException的其他异常。我想这意味着我试图拆箱VAL为Int64的时候它实际上是一个Int32?

Then when I try to cast as something other than Int32 InvalidCastException is thrown. I suppose this means that I am trying to unbox val as Int64 when it is actually an Int32?

不过似乎有些奇怪。无法投拆箱的值,然后尝试执行转换?

Still seems strange. Couldn't the cast unbox the value and then try to perform the cast?

类似的信息(显然这是可怕的过于简单,也许盒装类型是不知道,所以这是不可能的):

Something like (Obviously this is horribly oversimplified, maybe the boxed type isn't known so this isn't possible?):

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

有人(读:埃里克利珀)学校我这背后的推理。

Someone (read: Eric Lippert) School me on the reasoning behind this.

更新:从埃里克的博客,里德公布的链接,这是简洁的答案我一直在寻找

UPDATE: From Eric's Blog that Reed posted a link to this is the succinct answer I was looking for

......这将是一个巨大的数额code产生,那将是非常缓慢的code当然是如此之大,你会想要把它在其自己的方法,只是生成调用它。而不是做在默认情况下,总是产生code又慢,又大又脆弱,相反,我们已经决定,拆箱只能拆箱的确切类型。 如果你要调用的速度慢的方法,做所有的黏性物质,它的可用 - 你可以随时调用Convert.ToInt32,这确实所有的分析在运行时为您,我们为您提供的快速和$ P的选择$ pcise或缓慢而不严,并在合理的默认值是前者。如果你想后者则调用该方法......的

"...This would be a huge amount of code to generate, and it would be very slow. The code is of course so large that you would want to put it in its own method and just generate a call to it. Rather than do that by default, and always generate code that is slow, large and fragile, instead we’ve decided that unboxing can only unbox to the exact type. If you want to call the slow method that does all that goo, it’s available – you can always call Convert.ToInt32, which does all that analysis at runtime for you. We give you the choice between "fast and precise" or "slow and lax", and the sensible default is the former. If you want the latter then call the method...."

推荐答案

这是因为你不能拆箱,并在一次操作中执行转换。你必须拆箱的Int32值转换成一个Int32,并随后把它的类型。

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.

由于这个原因,这就需要给拆箱对象,然后转换成的Int64:

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;

埃里克利珀覆盖对此进行了详细在他的博客一篇名为再presentation和身份。