5

我试过了

 module Program
 {
  Main() : void
  { mutable x : byte = 0B;
    mutable y : byte = 0B;  
    x++;
    //y = x + 1;
    //y = x + 1B;
    //def one:byte=1;//   x = x + one;
  }
 }

无论我尝试哪一个,我都会收到以下错误消息。

错误 1 ​​个预期字节,在分配的值中得到 int:System.Int32 不是 System.Byte 的子类型 [简单要求]

我发现有效的唯一方法是

    y = ( x + 1 ):>byte

这有点花哨,只是添加一个。

为什么是这样?有没有更好的(阅读更短的方式)?

4

4 回答 4

8

与在 C# 中一样,在 Nemerle中 abyte和 a之和的结果是 a 。然而,与 C# 不同的是,Nemerle 试图使核心语言尽可能紧凑,将所有语法糖保留在标准宏库中。本着这种精神,and运算符是被翻译成正则加法的宏。byteint+=++

回答你的问题,(x + 1) :> byte就是这样做的方法。这实际上并不全是坏事,因为它让你的代码的读者知道你意识到溢出的危险并为此负责。

不过,如果您对此有强烈的感觉,您可以轻松编写自己的宏+=++宏来执行转换。它只需要几行代码。

于 2011-07-10T22:03:34.580 回答
2

It is because the CLR defines only a limited number of valid operands for the Add IL instruction. Valid are Int32, Int64, Single and Double. Also IntPtr but that tends to be disabled in many languages.

So adding a constant to a byte requires the byte to be converted to an Int32 first. The result of the addition is an Int32. Which doesn't fit back into a byte. Unless you use a bigger hammer. This is otherwise healthy, the odds that you overflow Byte.MaxValue are pretty large.

Note that there are languages that automatically cast, VB.NET is one of them. But it also automatically generates an OverflowException. Clearly not the one you are using, nor C#. This is a perf choice, the overflow test is not that cheap.

于 2011-07-10T21:33:42.190 回答
1

免责声明:我不知道 Nemerle,但我假设它在这方面的行为类似于 C#。

有一个更好更短的方法:不要使用字节。

你为什么首先使用它们?大多数时候,使用ints 的计算比使用 s 更快byte,因为今天的计算机已针对它们进行了优化。

于 2011-07-10T21:06:06.853 回答
0

这就是类型系统所做的。加法将值升级到 int,然后执行生成 int 的操作。也想过如果起始值为 255 会发生什么?

于 2011-07-10T21:09:18.660 回答