문제

Is there a difference in the returned values between Timespan(0,0,secs) and Timespan.FromSeconds(secs)?

It seems to me the difference is that FromSeconds accepts a double.

도움이 되었습니까?

해결책

Ultimately no, under the hood, TimeSpan deals with ticks.

Personally I would prefer to use TimeSpan.FromSeconds as it is completely clear what the intent is.

다른 팁

The parameter being a double in the second case is an important difference indeed: in some cases it can lead to an OverflowException. Quoting the documentation below.

TimeSpan Constructor (Int32, Int32, Int32):

The specified hours, minutes, and seconds are converted to ticks, and that value initializes this instance.

TimeSpan.FromSeconds Method:

The value parameter is converted to milliseconds, which is converted to ticks, and that number of ticks is used to intialize the new 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.

// 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

Even though i find the TimeSpan.FromSeconds method more readable, hence less error-prone, than the constructor.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top