C#溢出不工作?如何启用溢出检查? [英] C# Overflow not Working? How to enable Overflow Checking?

查看:278
本文介绍了C#溢出不工作?如何启用溢出检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#,并注意到当我有一个非常大的整数,并试图使它更大。相反,抛出一些类型的溢出错误,它只是将数字设置为最低可能的值(-2,147,483,648)我相信。



我想知道是否有一种方法启用Visual Studio中的溢出检查?

解决方案

您可以使用以下步骤启用算术溢出/下溢检查Visual Studio:



  1. 右键单击解决方案资源管理器中的项目,然后选择属性。 / li>
  2. 在构建选项卡上,单击高级按钮。 (向下)

  3. 检查检查算术溢出/下溢复选框。




这将抛出一个 System.OverflowException 发生溢出时,而不是通常将值更改为最小值。



没有算术溢出/下溢启用:

  int test = int.MaxValue; 
test ++;
//现在测试应等于-2,147,483,648(int.MinValue)

启用算术溢出/下溢:

  int test = int.MaxValue; 
test ++;
//System.OverflowException抛出

使用选中的块:

  checked 
{
int test = int.MaxValue;
test ++;
//System.OverflowException抛出
}

已检查的文档可用 here。感谢Sasha提醒我


I was working around with C# and noticed that when I had a very large integer and attempted to make it larger. Rather that throwing some type of overflow error, it simply set the number to the lowest possible value (-2,147,483,648) I believe.

I was wondering if there was a way to enable the overflow checking in Visual Studio?

解决方案

You can use the following steps to enable Arithmetic Overflow/Underflow checking in Visual Studio :

  1. Right click on your project in the Solution Explorer and select Properties.
  2. On the Build tab, click the Advanced button. (It's towards the bottom)
  3. Check the "Check for arithmetic overflow / underflow" check-box.

This will throw a System.OverflowException when the overflow occurs rather than it's usual operation of changing the value to a minimum value.

Without Arithmetic Overflow/Underflow enabled:

int test = int.MaxValue;
test++;
//Test should now be equal to -2,147,483,648 (int.MinValue)

With Arithmetic Overflow/Underflow enabled:

int test = int.MaxValue;
test++;
//System.OverflowException thrown

Using a checked block:

checked
{
    int test = int.MaxValue;
    test++;
    //System.OverflowException thrown
}

The documentation for checked is available here. (Thanks to Sasha for reminding me about it.)

这篇关于C#溢出不工作?如何启用溢出检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆