提问者:小点点

C#UInt64减法问题


为什么UInt64数据类型的减法有时会出现错误。我减少了秒数时间跨度,结果应该在1-10之间,但系统的结果可能是数百万甚至数十亿?错误?

private bool isReplayRequest(string kode, string rTs)
{
    if (System.Runtime.Caching.MemoryCache.Default.Contains(kode))
    {
        return true;
    }
    
    DateTime eStart = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc);
    TimeSpan cTs = DateTime.UtcNow - eStart;
    var stotalSeconds = Convert.ToUInt64(cTs.TotalSeconds);
    var rTotalSeconds = Convert.ToUInt64(rTs);
    
    if ((stotalSeconds - rTotalSeconds) > maxSeconds)
    {
        return true;
    }
    
    .... etc ....
}

在线问题(stotal秒-rTotal秒)


共1个答案

匿名用户

我不确定这是否能解决你的问题只是我的第一个想法

默认情况下,C#编译器不检查算术溢出

在Visual Studio中,您可以在项目的属性、构建部分、高级设置中启用此选项

在Visual Studio之外,这里是编译器设置

-已检查

<CheckForOverflowUnderflow>true</CheckForOverflowUnderflow>

法比奥