看看这段c#代码:

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

在字节(或短)类型上执行的任何数学运算的结果都隐式地转换回整数。解决方案是显式地将结果转换回一个字节:

byte z = (byte)(x + y); // this works

我想知道的是为什么?是建筑吗?哲学吗?

我们有:

Int + Int = Int 长+长=长 浮+浮=浮 Double + Double = Double

所以为什么不呢:

字节+字节=字节 空头+空头=空头?

一点背景知识:我正在对“小数字”(即< 8)执行一个长列表的计算,并将中间结果存储在一个大数组中。使用字节数组(而不是int数组)更快(因为缓存命中)。但是大量的字节强制转换散布在代码中,使得代码更加难以阅读。


当前回答

我认为这是一个关于哪种操作更常见的设计决策……如果byte+byte = byte,可能更多的人会被强制转换为int类型的结果所困扰。

其他回答

我记得曾经读过Jon Skeet(现在找不到了,我会继续找)关于字节如何实际上不会重载+操作符的内容。事实上,当像您的示例中那样添加两个字节时,每个字节实际上都被隐式转换为int。其结果显然是一个整型。至于为什么要这样设计,我将等待乔恩·斯基特自己发布:)

编辑:找到了!这里有关于这个话题的很棒的信息。

我怀疑c#实际上是在调用int上定义的运算符+(它返回一个int,除非你在一个检查块中),并隐式地将你的bytes/shorts都转换为int。这就是为什么行为看起来不一致。

我认为这是一个关于哪种操作更常见的设计决策……如果byte+byte = byte,可能更多的人会被强制转换为int类型的结果所困扰。

代码片段的第三行:

byte z = x + y;

实际上意味着

byte z = (int) x + (int) y;

因此,对字节没有+操作,字节首先被转换为整数,两个整数相加的结果是一个(32位)整数。

This was probably a practical decision on the part of the language designers. After all, an int is an Int32, a 32-bit signed integer. Whenever you do an integer operation on a type smaller than int, it's going to be converted to a 32 bit signed int by most any 32 bit CPU anyway. That, combined with the likelihood of overflowing small integers, probably sealed the deal. It saves you from the chore of continuously checking for over/under-flow, and when the final result of an expression on bytes would be in range, despite the fact that at some intermediate stage it would be out of range, you get a correct result.

另一种想法是:必须模拟这些类型上的溢出/欠流,因为它不会自然地发生在最可能的目标cpu上。何苦呢?