Dan*_*ani 1 c# floating-point int casting
这会抛出一个异常,表示源无法转换到目标:
int a = 1;
object b = (object)a;
float c = (float)b; // Exception here
Run Code Online (Sandbox Code Playgroud)
为什么?
您只能将盒装结构转换为确切类型,因此您需要先将int转换为int:
float c = (float)(int)b;
Run Code Online (Sandbox Code Playgroud)
但是,由于从int中隐式转换为float,您可以这样做:
float c = (int)b;
Run Code Online (Sandbox Code Playgroud)