byte + byte = int... why?(byte + byte = int ... 为什么?)
问题描述
看看这段 C# 代码:
Looking at this C# code:
byte x = 1;
byte y = 2;
byte z = x + y; // ERROR: Cannot implicitly convert type 'int' to 'byte'
对 byte(或 short)类型执行的任何数学运算的结果都会隐式转换回整数.解决方案是将结果显式转换回一个字节:
The result of any math performed on byte (or short) types is implicitly cast back to an integer. The solution is to explicitly cast the result back to a byte:
byte z = (byte)(x + y); // this works
我想知道为什么?它是建筑的吗?哲学?
What I am wondering is why? Is it architectural? Philosophical?
我们有:
int+int=intlong+long=longfloat+float=floatdouble+double=double
int+int=intlong+long=longfloat+float=floatdouble+double=double
为什么不呢:
字节+字节=字节short+short=short?
byte+byte=byteshort+short=short?
一点背景知识:我正在对小数"(即 < 8)执行一长串计算,并将中间结果存储在一个大数组中.使用 byte 数组(而不是 int 数组)更快(因为缓存命中).但是通过代码传播的大量字节转换使其更加难以阅读.
A bit of background: I am performing a long list of calculations on "small numbers" (i.e. < 8) and storing the intermediate results in a large array. Using a byte array (instead of an int array) is faster (because of cache hits). But the extensive byte-casts spread through the code make it that much more unreadable.
推荐答案
你的代码片段的第三行:
The third line of your code snippet:
byte z = x + y;
其实就是
byte z = (int) x + (int) y;
因此,对字节没有 + 操作,字节首先转换为整数,两个整数相加的结果是一个(32 位)整数.
So, there is no + operation on bytes, bytes are first cast to integers and the result of addition of two integers is a (32-bit) integer.
这篇关于byte + byte = int ... 为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:byte + byte = int ... 为什么?
基础教程推荐
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
