【问题标题】:Cant cast float to int if object如果对象不能将浮点数转换为int
【发布时间】:2011-05-20 03:46:03
【问题描述】:

这段代码运行良好

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

Console.Write(fd);

这段代码没有

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

Console.Write(fd);

跑步者中的什么规则导致这种情况发生?

【问题讨论】:

    标签: c# casting


    【解决方案1】:

    您可以将浮点数转换为 int,但不能将 boxed 浮点数转换为 int - 您必须先将其拆箱。

    int fd = (int)(float)jf;
    

    阅读 Eric Lippert 的帖子 Representation and Identity 了解更多详情。

    【讨论】:

      【解决方案2】:
      float ff = 5.5f; 
      object jf = ff;
      int fd = (int) jf;
      

      当您从 float 装箱到 object 时,实际类型 jf 是 float 并且您将装箱的 float 直接拆箱为运行时不接受的 int。

      所以您需要先拆箱以浮动,然后再次转换为 int。

      【讨论】:

        猜你喜欢
        • 2014-09-03
        • 2021-08-11
        • 1970-01-01
        • 2022-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-24
        • 2021-06-18
        相关资源
        最近更新 更多