byte + byte = int… why?

前端 未结 16 2111
长情又很酷
长情又很酷 2020-11-22 04:33

Looking at this C# code:

byte x = 1;
byte y = 2;
byte z = x + y; // ERROR: Cannot implicitly convert type \'int\' to \'byte\'

The result of

16条回答
  •  遥遥无期
    2020-11-22 05:18

    From .NET Framework code:

    // bytes
    private static object AddByte(byte Left, byte Right)
    {
        short num = (short) (Left + Right);
        if (num > 0xff)
        {
            return num;
        }
        return (byte) num;
    }
    
    // shorts (int16)
    private static object AddInt16(short Left, short Right)
    {
        int num = Left + Right;
        if ((num <= 0x7fff) && (num >= -32768))
        {
            return (short) num;
        }
        return num;
    }
    

    Simplify with .NET 3.5 and above:

    public static class Extensions 
    {
        public static byte Add(this byte a, byte b)
        {
            return (byte)(a + b);
        }
    }
    

    now you can do:

    byte a = 1, b = 2, c;
    c = a.Add(b);
    

提交回复
热议问题