运算不应溢出

更新:2007 年 11 月

TypeName

OperationsShouldNotOverflow

CheckId

CA2233

类别

Microsoft.Usage

是否重大更改

原因

某方法执行算术运算,但没有预先验证操作数以防止溢出。

规则说明

如果未首先验证操作数以确保运算结果不会超出所涉及数据类型的允许值范围,则不应执行算术运算。取决于执行上下文和涉及的数据类型,算术溢出可能导致 System.OverflowException 或结果的最高有效位被丢弃。

如何修复冲突

要修复与该规则的冲突,请在执行运算前验证操作数。

何时禁止显示警告

如果操作数的可能值永远不会导致算术运算溢出,则可以安全地禁止显示与该规则有关的警告。

冲突的示例

说明

下面示例中的方法使用一个与此规则冲突的整数。Visual Basic 要求禁用移除整数溢出选项来激发此规则。

代码

Imports System 

Public Module Calculator     

    Public Function Decrement(ByVal input As Integer) As Integer

        ' Violates this rule        
        input = input - 1         
        Return input

    End Function 

End Module
using System; 

namespace Samples
{    
    public static class Calculator    
    {        
        public static int Decrement(int input)        
        {             
            // Violates this rule            
            input--;             
            return input;        
        }    
    }
}

注释

如果向此示例中的方法传递了 MinValue,则操作将下溢。这会导致结果的最高有效位被丢弃。下面的代码演示这一过程。

[C#]

public static void Main()
{
    int value = int.MinValue;    // int.MinValue is -2147483648 
    value = Calculator.Decrement(value); 
    Console.WriteLine(value);
}

[VB]

Public Shared Sub Main()     
    Dim value = Integer.MinValue    ' Integer.MinValue is -2147483648 
    value = Calculator.Decrement(value) 
    Console.WriteLine(value) 
End Sub

Output

2147483647

使用输入参数验证进行修复

说明

下面的示例通过验证输入值来修复前面的冲突。

代码

Public Module Calculator

    Public Function Decrement(ByVal input As Integer) As Integer

        If (input = Integer.MinValue) Then _
            Throw New ArgumentOutOfRangeException("input", "input must be greater than Int32.MinValue")

        input = input - 1
        Return input

    End Function

End Module
using System; 

namespace Samples
{    
    public static class Calculator    
    {        
        public static int Decrement(int input)        
        {            
            if (input == int.MinValue)                
                throw new ArgumentOutOfRangeException("input", "input must be greater than Int32.MinValue");

            input--;             
            return input;        
        }    
    }
}

使用 Checked 块进行修复

说明

下面的示例通过封装 Checked 块中的操作来修复前面的冲突。如果操作导致溢出,将引发 System.OverflowException

请注意,Visual Basic 不支持 Checked 块。

代码

using System; 

namespace Samples
{    
    public static class Calculator    
    {        
        public static int Decrement(int input)        
        {            
            checked            
            {                
                input--;            
            }                        

            return input;        
        }    
    }
}

打开 Checked 运算上溢/下溢

如果在 C# 中打开 Checked 运算上溢/下溢,则等效于封装 Checked 块中的每个整数运算。

在 C# 中打开 Checked 运算上溢/下溢

  1. 在“解决方案资源管理器”中,右击项目并选择“属性”。

  2. 选择“生成”选项卡并单击“高级”。

  3. 选择“检查运算上溢/下溢”并单击“确定”。

请参见

参考

C# 运算符

Checked 和 Unchecked(C# 参考)

System.OverflowException