为什么FxCop的警告有关本C#code溢出(CA2233)?FxCop、code

2023-09-05 00:02:09 作者:崇凛

我有以下函​​数来获得从高字节的int和低字节:

I have the following function to get an int from a high-byte and a low-byte:

public static int FromBytes(byte high, byte low)
{
    return high * (byte.MaxValue + 1) + low;
}

当我分析了与FxCop的大会,我得到以下严重警告:

When I analyze the assembly with FxCop, I get the following critical warning:

CA2233:OperationsShouldNotOverflow   算术运算不应该   不先验证完成   操作数prevent溢出。

CA2233: OperationsShouldNotOverflow Arithmetic operations should not be done without first validating the operands to prevent overflow.

我不明白这到底是怎么可能溢出,所以我只是假设的FxCop正在过分热心。 我失去了一些东西?什么措施可以采取纠正我有什么(或者至少使FxCop的警告走开!)?

I can't see how this could possibly overflow, so I am just assuming FxCop is being overzealous. Am I missing something? And what steps could be taken to correct what I have (or at least make the FxCop warning go away!)?

推荐答案

随着丹尼尔A.白色 pointed出,你得到的消息,因为(byte.MaxValue + 1)溢出一个字节。

As Daniel A. White pointed out, you get the message because "(byte.MaxValue + 1)" overflows a byte.

但不是铸造和乘法,我只想转移位为已完成下面的code:

But instead of casting and multiplying, I would simply shift the bits as done in the code below:

public static int FromBytes(byte high, byte low) {
    return high << 8 | low;
}

作为一个副作用,此code可能会表现得更好。我没有检查所产生的IL或x86,看看编译器和/或抖动有足够的智慧,优化了原有的EX pression。

As a side effect, this code will probably perform better. I haven't checked the resulting IL or x86 to see if the compiler and/or the JITter are smart enough to optimize the original expression.