C#溢出不工作?如何启用溢出检查?
我在使用C#时注意到,当我有一个非常大的整数并试图将其变大时。与其抛出某种类型的溢出错误,不如简单地将数字设置为我认为可能的最低值(-2147483648)C#溢出不工作?如何启用溢出检查?,c#,.net,visual-studio,exception,overflow,C#,.net,Visual Studio,Exception,Overflow,我在使用C#时注意到,当我有一个非常大的整数并试图将其变大时。与其抛出某种类型的溢出错误,不如简单地将数字设置为我认为可能的最低值(-2147483648) 我想知道是否有办法在Visual Studio中启用溢出检查?您可以使用以下步骤在Visual Studio中启用算术溢出/下溢检查: 在解决方案资源管理器中右键单击项目,然后选择“属性” 在“生成”选项卡上,单击“高级”按钮。(在底部) 选中“检查算术溢出/下溢”复选框 当溢出发生时,这将抛出一个错误,而不是将值更改为最小值的常规操作 未
我想知道是否有办法在Visual Studio中启用溢出检查?您可以使用以下步骤在Visual Studio中启用算术溢出/下溢检查:
int test = int.MaxValue;
test++;
//Test should now be equal to -2,147,483,648 (int.MinValue)
int test = int.MaxValue;
test++;
//System.OverflowException thrown
checked
{
int test = int.MaxValue;
test++;
//System.OverflowException thrown
}
启用算术溢出/下溢:
int test = int.MaxValue;
test++;
//Test should now be equal to -2,147,483,648 (int.MinValue)
int test = int.MaxValue;
test++;
//System.OverflowException thrown
checked
{
int test = int.MaxValue;
test++;
//System.OverflowException thrown
}
使用选中的块:
int test = int.MaxValue;
test++;
//Test should now be equal to -2,147,483,648 (int.MinValue)
int test = int.MaxValue;
test++;
//System.OverflowException thrown
checked
{
int test = int.MaxValue;
test++;
//System.OverflowException thrown
}
checked的文档可用(感谢Sasha提醒我这一点)。您还可以使用
checked
关键字包装一条语句或一组语句,以便显式检查它们是否存在算术溢出。设置项目范围的属性有点风险,因为通常溢出是一个相当合理的预期。请注意,此编译器选项仅在代码中没有显式的选中的或未选中的上下文时适用。此外,它将影响生成的可执行文件,而不仅仅是在VisualStudio中进行调试。有关文档,请参见此处:@rionmoster和@Sasha-我不知道这两个功能中的任何一个。多亏了这两个。很好的一点,Sasha-我刚刚打开了一个关于checked语句的短博客:)链接很快就会出现。请注意,如果您只想检查表达式的一部分,而不是整个语句或一组语句,也可以在表达式上下文中使用“checked”。