为什么 FxCop 会警告此 C# 代码中的溢出 (CA2233)?
我有以下函数从高字节和低字节获取 int:
public static int FromBytes(byte high, byte low)
{
return high * (byte.MaxValue + 1) + low;
}
当我使用 FxCop 分析程序集时,我收到以下严重警告:
CA2233:操作不应溢出
算术运算不应该 没有首先验证就完成了 防止溢出的操作数。
我不明白这怎么可能溢出,所以我只是假设 FxCop 过于热心。
我错过了什么吗?可以采取哪些步骤来纠正我所遇到的问题(或者至少让 FxCop 警告消失!)?
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;
}
When I analyze the assembly with FxCop, I get the following critical warning:
CA2233: OperationsShouldNotOverflow
Arithmetic operations should not be
done without first validating the
operands to prevent overflow.
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!)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它以字节计算的方式进行它们。
试试这个
It is doing them as byte calculations.
Try this
字节加法和乘法结果都是整数。这里的最大值是 65535,不会溢出 int。只是压制错误。
obj 的类型为 int
试试这个:
没问题。
或者试试这个
Byte addition and mult results are ints. The max value here is 65535 which won't overflow an int. Just surpress the error.
obj has type int
Try this:
No problem.
or try this
正如 丹尼尔·怀特 指出,您收到消息是因为“(byte.MaxValue + 1)”溢出一个字节。
但我不会进行转换和乘法,而是简单地按照下面的代码中的方式移动位:
作为副作用,此代码可能会执行得更好。我还没有检查生成的 IL 或 x86 以查看编译器和/或 JITter 是否足够智能来优化原始表达式。
As Daniel A. White pointed out, you get the message because "(byte.MaxValue + 1)" overflows a byte.
But instead of casting and multiplying, I would simply shift the bits as done in the code below:
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.
以下是它最终停止对我抱怨 CA2233 的两种方法:
我认为这可能是规则中的一个错误。
Here's 2 ways that it finally stopped whining about CA2233 for me:
I think it might be a bug in the rule.