我有这段代码,但由于某种原因它不起作用。我不明白。怎么了?
byte dog = (byte)2*byte.Parse("2");
我在 LinqPad 中遇到此异常:“无法将类型‘int’隐式转换为‘byte’。存在显式转换(是否缺少强制转换?)。”
另外,编写这段代码的正确方法是什么?谢谢。
最佳答案
sbyte、byte、ushort 和 short 上的所有算术运算都被扩展为int。 比如第三行会给出编译错误:
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
关于c# - 由于某种原因,字节乘以字节是 int。为什么?无法将类型 'int' 隐式转换为 'byte' 。存在显式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28135143/