简体   繁体   中英

Cant cast float to int if object

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM