Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 长期误算_C# - Fatal编程技术网

C# 长期误算

C# 长期误算,c#,C#,下面代码中返回-666167296、time=42和TimeStyle.Days的长数据类型有什么问题 private long ConvertToMilliSeconds(int time, TimeStyle style) { long t = 0; switch (style) { case TimeStyle.Millisecons: t = time;

下面代码中返回-666167296、time=42和TimeStyle.Days的长数据类型有什么问题

    private long ConvertToMilliSeconds(int time, TimeStyle style)
    {
        long t = 0;
        switch (style)
        {
            case TimeStyle.Millisecons:
                t = time;
                break;
            case TimeStyle.Seconds:
                t = time * 1000;
                break;
            case TimeStyle.Minutes:
                t = time * 1000 * 60;
                break;
            case TimeStyle.Hours:
                t = time * 1000 * 60 * 60;
                break;
            case TimeStyle.Days:
                t = time * 86400000;
                break;
            default:
                break;
        }

        return t;
    }

time
是一个
int
,当您进行如下计算时,将其设置为
long
或转换为
long
*86400000L

t = time * 86400000
t
是一个
long
的事实是不相关的:赋值运算符右侧的算术是以32位执行的,因为
time
86400000
都是
int
值。您需要在
long
算术中执行该操作以避免溢出

考虑到
long
的毫秒数是合理的,我将
t
更改为
long
。如果无法识别枚举值,我也会抛出异常,而不仅仅是返回0:

private static long ConvertToMilliSeconds(long time, TimeStyle style)
{
    switch (style)
    {
        // Note: fixed typo in enum name
        case TimeStyle.Milliseconds: return time;
        case TimeStyle.Seconds:      return time * 1000;
        case TimeStyle.Minutes:      return time * 1000 * 60;
        case TimeStyle.Hours:        return time * 1000 * 60 * 60;
        case TimeStyle.Days:         return time * 86400000;
        default:
            throw new ArgumentOutOfRangeException("style");
    }
}
您可能还希望将这些值更改为常量:

private const long MillisecondsPerSecond = 1000;
private const long MillisecondsPerMinute = MillisecondsPerSecond * 60;
private const long MillisecondsPerHour = MillisecondsPerMinute * 60;
private const long MillisecondsPerDay = MillisecondsPerHour * 24;
。。。并使用这些方法


最后,为了避免在值的单位错误时出现任何可能的混淆,您可能只需要使用
TimeSpan
来开始。。。如果你仍然觉得日期/时间API很痛苦,你可能想看看我的库:)

42*86400000太长了。如果在visual studio中键入,则会出现编译器错误:

在检查模式下,操作在编译时溢出


这个答案是不正确的;42*86400000不会太长时间。相反,42*86400000是一个
int
表达式,结果对于int来说太大,这就是为什么会出现编译器错误。