为什么FxCop警告此C#代码中的溢出(CA2233)?
我有以下函数从高字节和低字节获取一个int:
public static int FromBytes(byte high, byte low) { return high * (byte.MaxValue + 1) + low; }
当我使用FxCop分析程序集时,我收到以下严重警告:
CA2233:OperationsShouldNotOverflow
如果没有首先validation操作数以防止溢出,则不应进行算术运算。
我无法看到这可能会溢出,所以我只是假设FxCop过于热心。
我错过了什么吗? 我可以采取哪些步骤来纠正我所拥有的(或至少使FxCop警告消失!)?
正如Daniel A. White所 指出的 ,你得到的消息是因为“(byte.MaxValue + 1)”溢出了一个字节。
但是,我只需按照以下代码中的步骤移动位,而不是进行转换和乘法运算:
public static int FromBytes(byte high, byte low) { return high << 8 | low; }
作为副作用,此代码可能会表现更好。 我没有检查生成的IL或x86,看看编译器和/或JITter是否足够智能以优化原始表达式。
它将它们作为字节计算。
试试这个
return (int)high * ((int)byte.MaxValue + 1) + (int)low;
字节添加和多个结果是整数。 这里的最大值是65535,不会溢出int。 只是压抑错误。
byte a = 1; byte b = 2; object obj = a + b
obj的类型为int
试试这个:
byte high = 255; byte low = 255; checked { int b = high * (byte.MaxValue + 1) + low; }
没问题。
或试试这个
这里有两种方式让它最终停止为我抱怨CA2233:
public static int FromBytes(byte high, byte low) { int h = high; return h * (byte.MaxValue + 1) + low; } public static int FromBytes2(byte high, byte low) { unchecked { return high * (byte.MaxValue + 1) + low; } }
我认为这可能是规则中的一个错误。