我有以下代码:
foreach (byte b in bytes)
{
byte inv = byte.MaxValue - b;
// Add the new value to a list....
}
Run Code Online (Sandbox Code Playgroud)
当我这样做时,我收到以下错误:
Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)
该语句的每个部分都是一个字节.为什么C#想要转换byte.MaxValue - b为int?
如果没有铸造你不应该这样做吗?(即我不希望有这样做:byte inv = (byte) (byte.MaxValue - b);)
根据C# 语言参考:
因为赋值运算符右侧的算术表达式默认计算结果为 int。
其原因可能是因为您的处理器访问 4 字节内存地址的速度比访问 1 字节内存地址的速度更快,因此算术运算符被定义为处理 4 字节操作数。