【发布时间】:2019-07-19 15:00:09
【问题描述】:
我在 C# 中有一段简单的代码,用于在将类型的 MaxValue 添加 1 时显示溢出错误。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
byte a = byte.MaxValue;
byte b = 1;
Console.WriteLine("Max+1 is : {0}", a+b);
Console.ReadLine();
}
}
}
但不是溢出和错误结果,而是生成正确的值:256 为什么? 而 C# 中字节变量的最大值为 255。 我错了吗?
【问题讨论】:
-
为什么
string str = (255 + 1).ToString();会抛出错误? -
添加
byte c = a + b;似乎深入了解了添加的完成方式:“无法将类型'int'隐式转换为'byte'。存在显式转换(您是否缺少cast?)" - 似乎byte被隐式转换为int以进行此添加。 -
您只是添加这两个值并显示它们,而不是将它们分配给一个字节。
-
当您添加字节时,它们会隐式转换为整数。查看stackoverflow.com/questions/941584/byte-byte-int-why