Confused by Boxing. Casting -1 to Int64 throws InvalidCastException

半世苍凉 提交于 2019-12-03 06:20:14
Reed Copsey

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.

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;

Eric Lippert covered this in detail on his blog post titled Representation and Identity.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!