简体   繁体   English

Timespan(0,0,secs)或Timespan.FromSeconds(secs)

[英]Timespan(0,0,secs) or Timespan.FromSeconds(secs)

Is there a difference in the returned values between Timespan(0,0,secs) and Timespan.FromSeconds(secs) ? Timespan(0,0,secs)Timespan.FromSeconds(secs)之间的返回值是否存在差异?

It seems to me the difference is that FromSeconds accepts a double . 在我看来,不同之处在于FromSeconds接受了一个double精度数。

Ultimately no, under the hood, TimeSpan deals with ticks. 最终没有,在引擎盖下, TimeSpan处理滴答声。

Personally I would prefer to use TimeSpan.FromSeconds as it is completely clear what the intent is. 我个人更喜欢使用TimeSpan.FromSeconds因为它完全清楚意图是什么。

The parameter being a double in the second case is an important difference indeed: in some cases it can lead to an OverflowException . 在第二种情况下,参数是double精度确实是一个重要的区别:在某些情况下,它可能导致OverflowException Quoting the documentation below. 引用下面的文档。

TimeSpan Constructor (Int32, Int32, Int32) : TimeSpan构造函数(Int32,Int32,Int32)

The specified hours, minutes, and seconds are converted to ticks, and that value initializes this instance. 指定的小时,分​​钟和秒将转换为刻度,并且该值初始化此实例。

TimeSpan.FromSeconds Method : TimeSpan.FromSeconds方法

The value parameter is converted to milliseconds, which is converted to ticks, and that number of ticks is used to intialize the new TimeSpan. value参数转换为毫秒,转换为刻度,并且该刻度数用于初始化新TimeSpan。 Therefore, value will only be considered accurate to the nearest millisecond. 因此,仅将值视为精确到最接近的毫秒。 Note that, because of the loss of precision of the Double data type, this can generate an OverflowException for values that are near but still in the range of either MinValue or MaxValue, This is the cause of an OverflowException, for example, in the following attempt to instantiate a TimeSpan object. 请注意,由于Double数据类型的精度损失,这可能会为接近但仍在MinValue或MaxValue范围内的值生成OverflowException。这是OverflowException的原因,例如,在下面尝试实例化TimeSpan对象。

 // The following throws an OverflowException at runtime TimeSpan maxSpan = TimeSpan.FromSeconds(TimeSpan.MaxValue.TotalSeconds); 

You could test it easily: 你可以轻松测试它:

int secs = 10;
var ts = new TimeSpan(0, 0, secs);
var ts2 = TimeSpan.FromSeconds(secs);
if(ts == ts2)
{
    Console.WriteLine("Equal");
}
else
{
   Console.WriteLine("Not Equal");
}

Output is: Equal 输出是: Equal

Even though i find the TimeSpan.FromSeconds method more readable, hence less error-prone, than the constructor. 即使我发现TimeSpan.FromSeconds方法比构造函数更具可读性,因此更不容易出错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM