Cant cast float to int if object

左心房为你撑大大i 提交于 2019-12-12 10:38:18

问题


This code runs fine

float ff = 5.5f;
int fd = (int) ff;

Console.Write(fd);

Where as this code doesnt

float ff = 5.5f;
object jf = ff;
int fd = (int) jf;

Console.Write(fd);

What rule in the runner causes this to happen?


回答1:


You can cast a float to an int, but you can't cast a boxed float to an int - you have to unbox it first.

int fd = (int)(float)jf;

Read Eric Lippert's post Representation and Identity for more details.




回答2:


float ff = 5.5f; 
object jf = ff;
int fd = (int) jf;

here when you box from float to object , actual type which jf is float and you are unboxing an boxed float directly to int which is not accepted by the runtime.

so you need to first unboxed to float and then cast once again to int.



来源:https://stackoverflow.com/questions/4352697/cant-cast-float-to-int-if-object

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