在 C# 中使用时间跨度或表示时间跨度的整数值之间的区别

difference between using timespan or integer value representing the timespan in c#

我有一个代码,我在其中计算日期之间的一些间隔,为此我有一个定义的间隔时间,我将其添加到一个日期,为此我看到了 2 种方法,但我不明白区别,对我来说它们是一样的:

var timespan = new TimeSpan(0, 0, 5);
var d1 = new DateTime(2010, 1, 1, 8, 0, 15);

var newDateWithTimeSpan = d1.Add(timespan);
var newDateWithSeconds = d1.AddSeconds(5);

Console.WriteLine(newDateWithTimeSpan);
Console.WriteLine(newDateWithSeconds);

不,计算新 DateTime 值的两种方法没有区别。通常有多种方式来表达相同的意图,尤其是 DateTime。 (例如,您可以使用 d1 + timespan 作为另一个选项。)

虽然这不是 实际 实现,但您可以想象 AddSeconds 是这样实现的:

public DateTime AddSeconds(double seconds) =>
    this.Add(TimeSpan.FromSeconds(seconds));

这只是一个方便的方法。

我认为在您的代码中使用 TimeSpan.FromSeconds 是表达 "I want to create a TimeSpan that represents 5 seconds" 的更清晰的方式,但这是一个稍微不同的问题。