如果 byte + byte = int 为什么 int + int 不是 short/long?在 C#
if byte + byte = int why int + int is not short/long? in C#
byte num1 = 5;
byte num2 = 6;
byte res = num1 + num2;
//Adding bytes asks for a explicit cast to int - "Cannot Implicitly Convert 'int' to 'byte'
这可以通过假设算术运算导致溢出的情况来证明。那么,如果情况确实如此,那么 int 呢?
int num1 = 2;
int num2 = 4;
int res = num1 + num2;
// This works, but when we take the previous assumption to consideration here
// here int may also lead to overflow right
所以这也应该抛出一个正确的转换错误,它应该要求 long and
链条继续对吗?
已经有另一个与此类似的 Whosebug 问题,但它没有回答这个问题。 byte + byte = int... why?
仅仅因为这样“可以证明”,并不意味着那就是原因。
埃里克·利珀特(Eric Lippert)在对您链接的问题的评论中清楚地表明了这一点:
The various musings below are a reasonable approximation of the design considerations. More generally: I don't think of bytes as "numbers"; I think of them as patterns of bits that could be interpreted as numbers, or characters, or colors or whatever. If you're going to be doing math on them and treating them as numbers, then it makes sense to move the result into a data type that is more commonly interpreted as a number.
byte num1 = 5;
byte num2 = 6;
byte res = num1 + num2;
//Adding bytes asks for a explicit cast to int - "Cannot Implicitly Convert 'int' to 'byte'
这可以通过假设算术运算导致溢出的情况来证明。那么,如果情况确实如此,那么 int 呢?
int num1 = 2;
int num2 = 4;
int res = num1 + num2;
// This works, but when we take the previous assumption to consideration here
// here int may also lead to overflow right
所以这也应该抛出一个正确的转换错误,它应该要求 long and 链条继续对吗?
已经有另一个与此类似的 Whosebug 问题,但它没有回答这个问题。 byte + byte = int... why?
仅仅因为这样“可以证明”,并不意味着那就是原因。
埃里克·利珀特(Eric Lippert)在对您链接的问题的评论中清楚地表明了这一点:
The various musings below are a reasonable approximation of the design considerations. More generally: I don't think of bytes as "numbers"; I think of them as patterns of bits that could be interpreted as numbers, or characters, or colors or whatever. If you're going to be doing math on them and treating them as numbers, then it makes sense to move the result into a data type that is more commonly interpreted as a number.