In C# assigning result of addition of two byte variables to another byte variable generates error, can be assigned only to int variable
我有以下代码-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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); } } } |
输出:
1 2 3 4 5 6 | System.Byte System.Byte System.Byte 10 20 30 |
但如果使用
1 | (9,14): error CS0266: Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?) |
但如代码所示,编译器将
那么,为什么两个字节的相加会生成需要显式类型转换的int?
这是一个隐式转换的例子。
此链接进一步说明:
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).