在c#中转换对象类型

Tim*_*Tim 7 c# casting

我今天遇到了一个问题,我不完全确定为什么它不起作用.

以下代码示例将崩溃:

static void Main(string[] args)
{
     int i32 = 10;
     object obj = i32;
     long i64 = (long)obj;
}
Run Code Online (Sandbox Code Playgroud)

这将导致InvalidCastException.为什么这不起作用?C#不够聪明,不知道该对象实际上是int类型吗?

我已经提出了一个解决方法,但我很好奇为什么上面的代码示例首先不起作用.

蒂姆,谢谢

Ani*_*Ani 9

从盒装Int32到Int64没有可用的强制转换.使中间转换int应该起作用,因为编译器愿意生成这个:

// verify obj is a boxed int, unbox it, and perform the *statically*
// known steps necessary to convert an int to a long
long i64 = (long) ((int)obj);
Run Code Online (Sandbox Code Playgroud)

但不是(假设)这个:

// Find out what type obj *actually* is at run-time and perform 
// the-known-only-at-run-time steps necessary to produce  
// a long from it, involving *type-specific* IL instructions  
long i64 = (long)obj; 
Run Code Online (Sandbox Code Playgroud)

这是Eric Lippert关于此的博客文章.