由于某种原因,字节乘以字节是 int。为什么?无法将类型 'int' 隐式转换为 'byte'。存在显式转换

Byte multiplied by byte is int for some reason. Why? Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists

我有这段代码,但由于某种原因无法使用。我不明白。怎么了?

byte dog = (byte)2*byte.Parse("2");

我在 LinqPad 中得到这个异常:"Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)."

另外,这段代码的正确写法是什么?谢谢

将一个字节值与另一个字节值相乘对于大多数可能的结果将呈现一个不适合字节的值。极端情况是最大值乘积 255 * 255 - 虽然每个因子适合一个字节,但乘积需要一个整数才能适应。

sbyte、byte、ushort 和 short 上的所有算术运算 widenedint. 比如第三行会给出编译错误:

byte b1 = 1;
byte b2 = 2;
byte b3 = (b1 * b2); // Exception, Cannot implicitly convert type 'int' to 'byte
byte b4 = (byte)(b1 * b2); // everything is fine

因此,将您的代码更改为:

byte dog = (byte)((byte)2*byte.Parse("2"));

更多信息Look at this SO question

那是因为,从编译器的角度来看,您试图仅将第一个乘数转换为 byte,而不是整个结果。这是因为 c#

中的 operators precedence

试试这个:

byte dog = (byte) (2*byte.Parse("2"));

你还应该注意,你可以得到一个大于maximum byte value的整数(这是一个等于255的const,并且这种类型转换会丢失数据。