时间跨度FromMilliseconds奇怪的执行?跨度、奇怪、时间、FromMilliseconds

2023-09-03 00:21:12 作者:辣逼,小心!

我最近遇到了.NET时间跨度执行一些wird行为。

I recently encountered some wird behaviour in the .net timespan implementation.

        TimeSpan test = TimeSpan.FromMilliseconds(0.5);
        double ms = test.TotalMilliseconds; // Returns 0

该FromMilliseconds采用双作为参数。然而,似乎该值在内部取整。

The FromMilliseconds takes a double as parameter. However, it seems the value is rounded internally.

如果我实例化一个新的时间跨度有5000蜱(0.5毫秒),TotalMilliseconds的值是正确的。

If I instantiate a new timespan with 5000 ticks (.5 ms), the value of TotalMilliseconds is correct.

看着反射器的时间跨度执行显示,输入实际上是在浇铸长。

Looking at the TimeSpan implementation in reflector reveals that the input is in fact casted to a long.

为什么微软设计FromMilliseconds方法采取双重一个参数,而不是一个很长(因为双值是无用的给这个实现)?

Why did Microsoft design the FromMilliseconds method to take a double a parameter instead of a long (since a double value is useless given this implementation)?

推荐答案

首先考虑的是不知道他们为什么选择的双的作为返回值。使用的长的将是一个显而易见的选择。虽然已经是一个完美的属性,它是长,蜱是毫不含糊的以100纳秒为单位。但是,他们挑双,可能与打算返回一个分数值。

The first consideration is wondering why they selected a double as the return value. Using long would have been an obvious choice. Although there already is a perfectly good property that is long, Ticks is unambiguous with a unit of 100 nanoseconds. But they picked double, probably with the intention to return a fractional value.

这可是创造了一个新的问题,这就是一个可能是后来才发现的。双只能存储15显著数字。一时间跨度可以存储万年。它的非常的需要,从时间跨度转换成毫秒,然后再返回到时间跨度,并得到相同的值。

That however created a new problem, one that was possibly only discovered later. A double can store only 15 significant digits. A TimeSpan can store 10,000 years. It is very desirable to convert from TimeSpan to milliseconds, then back to TimeSpan and get the same value.

这是不可能与双。做数学:万年大致是10000×365.4×24×3600×1000 = 315,705,600,000,000毫秒。报数15位,最好的双能做到的,你得到的完全的一毫秒为可仍然没有存储舍入误差的最小单位。任何额外的数字将随机噪声。

That isn't possible with a double. Doing the math: 10,000 years is roughly 10000 x 365.4 x 24 x 3600 x 1000 = 315,705,600,000,000 milliseconds. Count off 15 digits, best a double can do, and you get exactly one millisecond as the smallest unit that can still be stored without round-off error. Any extra digits will be random noise.

插满了进退两难的境地,设计师(测试?)已经从时间跨度转换为毫秒时四舍五入的价值之间做出选择。或者从毫秒到时间跨度会在以后做。他们选择了提前做到这一点,一个勇敢的决定。

Stuck between a rock and a hard place, the designers (testers?) had to choose between rounding the value when converting from TimeSpan to milliseconds. Or to do it later when going from milliseconds to TimeSpan. They chose to do it early, a courageous decision.

通过蜱财产和乘以1E-4中得到毫秒解决您的问题。

Solve your problem by using the Ticks property and multiplying by 1E-4 to get milliseconds.