.NET / C# - 允许整数溢出
最近我开始制作一个项目容器,每次用户尝试将项目添加到容器中时。如果以某种方式存在相同的项目类型,它会将它们堆叠在一起,但有一个限制,即 int.MaxValue
如果我尝试:
if (2147483647 + 2147483647 > int.MaxValue)
这会给我以下错误:
The operation overflows at compile time in checked mode
所以我尝试使用 unchecked 关键字,如下所示:
unchecked
{
if (2147483647 + 2147483647 > int.MaxValue)
{
}
}
但这根本不显示触发 if 语句(我猜它包含逻辑 AND 运算符?)
还有其他方法可以做到这一点吗? (不使用 int64 等)
Recently i started making a item container, and every time the user tries to add an item into the container. If somehow the same item type exists, it'll stack them on top of each other, but there's a limit, which is int.MaxValue
and if i tried:
if (2147483647 + 2147483647 > int.MaxValue)
That would give me the following error:
The operation overflows at compile time in checked mode
So i tried to use the unchecked keyword like so:
unchecked
{
if (2147483647 + 2147483647 > int.MaxValue)
{
}
}
but this doesn't show trigger the if statement at all (I'm guessing it's wrapped around a Logical AND operator?)
Is there other ways to do this? (without using something like a int64, etc)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果 int 运算溢出,则不会测试大于
Int32.MaxValue
的值。如果您希望该条件成立,请使用长整型。
或者,使用 uint。
If an int operation overflows its not going to test greater than
Int32.MaxValue
.If you want that condition to be true, use longs.
Alternatively, use
uint
s.如果不需要位空间的负半部分,请尝试将两者都转换为 uint (无符号)。相同的位宽,只是在 Int.MaxValue 之后不会滚动负值(例如,它是 int.MaxValue 大小的 2 倍)
Try casting both to uint (unsigned) if you don't need the negative half of the bitspace. Same bit width, just doesn't roll negative after Int.MaxValue (eg, it's 2x the magnitude of int.MaxValue)
将其扔到未检查的块中:
https://learn.microsoft.com/en- us/dotnet/csharp/language-reference/keywords/unchecked
Throw it into an unchecked block:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/unchecked
if 条件未得到的主要原因是,由于
int
溢出,添加2147483647 + 2147483647
将导致-2
unchecked
块。这就是您的 if 条件
2147483647 + 2147483647 > 的原因int.MaxValue 永远不会为真,因为它会被计算为 -2 > int.MaxValue
,这不是真的。The main reason your if condition isn't getting is because the addition of
2147483647 + 2147483647
will result in-2
because of overflows ofint
in theunchecked
block.This is the reason your if condition
2147483647 + 2147483647 > int.MaxValue
is never going to be true because it'll get evaluated to-2 > int.MaxValue
, which isn't true.