【问题标题】:Byte multiplied by byte is int for some reason. Why? Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists由于某种原因,字节乘以字节是 int 。为什么?无法将类型“int”隐式转换为“byte”。存在显式转换
【发布时间】:2015-03-23 23:33:57
【问题描述】:

我有这段代码,但由于某种原因它不起作用。我不明白。怎么了?

byte dog = (byte)2*byte.Parse("2");

我在 LinqPad 中遇到此异常:“无法将类型 'int' 隐式转换为 'byte'。存在显式转换(您是否缺少强制转换?)。”

另外,编写此代码的正确方法是什么?谢谢。

【问题讨论】:

  • 试试byte dog =(byte)(2*byte.Parse("2"));

标签: c# .net casting type-conversion


【解决方案1】:

将一个字节值与另一个字节值相乘对于大多数可能的结果将呈现一个不适合一个字节的值。极端情况是最大值乘积 255 * 255 - 虽然每个因子都适合一个字节,但乘积需要一个整数才能适合。

【讨论】:

    【解决方案2】:

    sbyte、byte、ushort 和 short 上的所有算术运算都加宽int。 比如第三行会报编译错误:

    byte b1 = 1;
    byte b2 = 2;
    byte b3 = (b1 * b2); // Exception, Cannot implicitly convert type 'int' to 'byte
    byte b4 = (byte)(b1 * b2); // everything is fine
    

    因此,将您的代码更改为:

    byte dog = (byte)((byte)2*byte.Parse("2"));
    

    更多信息Look at this SO question

    【讨论】:

      【解决方案3】:

      这是因为,根据编译器的意见,您只是尝试将byte 转换为第一个乘数,而不是整个结果。这是因为 c# 中的operators precedence

      试试这个:

      byte dog = (byte) (2*byte.Parse("2"));
      

      另外你应该注意,你可以得到一个大于maximum byte value的整数(这是一个等于255的常量,这样的类型转换会丢失数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-18
        • 1970-01-01
        • 1970-01-01
        • 2011-02-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多