在 C# 中,将两个字节变量相加的结果分配给另一个字节变量会产生错误,只能分配给 int 变量

In C# assigning result of addition of two byte variables to another byte variable generates error, can be assigned only to int variable

我有以下代码-

using System;

namespace MyApp {
class Program {
    static void Main() {
        byte x = 10, y = 20;
        Console.WriteLine(x.GetType());
        Console.WriteLine(y.GetType());
        //byte z = (x+y); Error: (9,14): error CS0266: 
        //Cannot implicitly convert type 'int' to 'byte'. 
        //An explicit conversion exists (are you missing a cast?)
        byte z = (byte)(x+y);
        Console.WriteLine(z.GetType());
        Console.WriteLine(x);
        Console.WriteLine(y);
        Console.WriteLine(z);
    }
}
}

输出:

System.Byte
System.Byte
System.Byte
10
20
30

但是,如果使用 byte z = x+y,它会生成错误 -

而不是显式类型转换
(9,14): error CS0266: Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)

但是如代码所示,编译器将 xy 读取为字节。

那么,为什么两个字节相加生成的 int 需要显式类型转换?

这是 Implicit Conversion 的示例。

这 link 进一步解释:

https://blogs.msdn.microsoft.com/oldnewthing/20040310-00/?p=40323

People complain that the following code elicits a warning:

byte b = 32; byte c = ~b; // error CS0029: Cannot implicitly convert type 'int' to 'byte'

"The result of an operation on 'byte' should be another 'byte', not an 'int'," they claim.

Be careful what you ask for. You might not like it.

Suppose we lived in a fantasy world where operations on 'byte' resulted in 'byte'.

byte b = 32; byte c = 240; int i = b + c; // what is i?

In this fantasy world, the value of i would be 16! Why? Because the two operands to the + operator are both bytes, so the sum "b+c" is computed as a byte, which results in 16 due to integer overflow. (And, as I noted earlier, integer overflow is the new security attack vector.)

Similarly,

int j = -b;

would result in j having the value 224 and not -32, for the same reason. ... In our imaginary world, this code would return incorrect results once the total number of games played exceeded 255. To fix it, you would have to insert annoying int casts.

return ((int)captain.Wins + cocaptain.Wins) >= ((int)captain.Games + cocaptain.Games) / 2;

So no matter how you slice it, you're going to have to insert annoying casts. May as well have the language err on the side of safety (forcing you to insert the casts where you know that overflow is not an issue) than to err on the side of silence (where you may not notice the missing casts until your Payroll department asks you why their books don't add up at the end of the month).