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

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

问题描述

我正在周围的C#和注意到,当我有一个非常大的整数,并试图使其变大。宁可抛出一些类型的溢出错误的,它只是设置的数量可能的最低值(2,147,483,648),我相信。

我在想,如果有一种方法,使溢出检查在Visual Studio?

解决方案

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

  
      
  1. 右键单击在解决方案资源管理器中的项目并选择属性。
  2.   
  3. 在生成选项卡,单击高级按钮。 (这是对底部)
  4.   
  5. 检查检查算术溢/下溢复选框。
  6.   

这将抛出一个<一个href="http://msdn.microsoft.com/en-us/library/system.overflowexception.aspx"><$c$c>System.OverflowException当溢出发生时,而不是它的改变值到最低值的通常的操作。

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

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

算术溢/下溢启用:

 内部测试= int.MaxValue;
测试++;
//System.OverflowException抛出
 

使用检查块:

 检查
{
    INT测试= int.MaxValue;
    测试++;
    //System.OverflowException抛出
}
 

的文档检查,请这里感谢萨沙提醒我一下吧。的)

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天全站免登陆