C#溢出不起作用? 如何启用溢出检查?
我正在使用C#,并注意到当我有一个非常大的整数并试图使它变大。 而是抛出某种类型的溢出错误,它只是将数字设置为我认为的最低可能值(-2,147,483,648)。
我想知道是否有办法在Visual Studio中启用溢出检查?
您可以使用以下步骤在Visual Studio中启用算术溢出/下溢检查:
- 在Solution Explorer中右键单击您的项目,然后选择Properties。
- 在“生成”选项卡上,单击“高级”按钮。 (它在底部)
- 选中“检查算术溢出/下溢”复选框。
这将在发生溢出时抛出System.OverflowException
,而不是通常将值更改为最小值的操作。
未启用算术溢出/下溢:
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 }
可在此处获取已检查的文档。 ( 感谢Sasha提醒我这件事。 )