字节乘以字节的数据类型为int的某些原因。为什么?无法隐式转换类型'诠释'到'字节'。显式转换存在 [英] Byte multiplied by byte is int for some reason. Why? Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists
问题描述
我有这个code,并没有出于某种原因。我不明白。什么是错的?
I have this code and it doesn't work for some reason. I don't understand it. What is wrong?
byte dog = (byte)2*byte.Parse("2");
我得到这个异常LinqPad:无法隐式转换类型'诠释'到'字节'一个显式转换存在(是否缺少强制转换?)。
I get this exception in LinqPad: "Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)."
还有什么是正确的方式来写这个code?谢谢你。
Also what is the right way to write this code? Thanks.
推荐答案
上的为sbyte,字节,USHORT,总之所有的算术运算的是扩大为 INT 。 例如,第三行会给编译器错误:
All arithmetic operations on sbyte, byte, ushort, and short are widened to int. For example, the third line will give compiler error:
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
所以,改变你的code为:
So, change your code as:
byte dog = (byte)((byte)2*byte.Parse("2"));
有关详细信息的<一个href="http://stackoverflow.com/questions/24371868/why-must-a-short-be-converted-to-an-int-before-arithmetic-operations-in-c-and-c">Look在此等问题
这篇关于字节乘以字节的数据类型为int的某些原因。为什么?无法隐式转换类型'诠释'到'字节'。显式转换存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!