c# - 为什么使用 TimeSpan.CompareTo() 而不是 < > 或 =

标签 c# .net timespan compareto

我查看了一些 Microsoft 的 Kinect 传感器代码示例,无意中发现了以下行。

TimeSpan zeroDuration = TimeSpan.FromSeconds(0.0);
TimeSpan timeRemaining = ...;

if (timeRemaining.CompareTo(this.zeroDuration) > 0)
{
}

我了解 CompareTo() 在排序等场景中的用处,但为什么要在条件 if() 中使用它而不是更直接的方法?

if (timeRemaining > this.zeroDuration)
{
}

PS:如果它来自任何其他来源,我会持保留态度,但考虑到代码的一般质量,假设有一个原因

最佳答案

两者在内部做同样的事情。比较 Ticks 并返回结果。

public int CompareTo(TimeSpan value) {
    long t = value._ticks;
    if (_ticks > t) return 1;
    if (_ticks < t) return -1;
    return 0;
}

 public static bool operator <(TimeSpan t1, TimeSpan t2) {
            return t1._ticks < t2._ticks;
}

唯一的原因可能是 CompareTo 的另一个过载,它接收一个 object 类型参数检查 null 然后比较。实现方式如下:

public int CompareTo(Object value) {
            if (value == null) return 1;
            if (!(value is TimeSpan))
                throw new ArgumentException(Environment.GetResourceString("Arg_MustBeTimeSpan"));
            long t = ((TimeSpan)value)._ticks;
            if (_ticks > t) return 1;
            if (_ticks < t) return -1;
            return 0;
        }

源代码来自:Reference Source .NET Framework 4.5.1 - Microsoft

关于c# - 为什么使用 TimeSpan.CompareTo() 而不是 < > 或 =,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23088940/

相关文章:

c# - 为 C#/Mono Launcher 创建 webView

c#.net 启动画面加载

c# - 使用 C# 和 Selenium 进行 Nunit 参数化

c# - 为什么 C# 没有轻量级异常?

.net - 通过查看 MSIL 确定 .Net 可执行文件调用的程序集/DLL?

c# - 如何允许用户在 PropertyGrid 中设置表达式来确定属性值

c# - 在磁盘上找到 Blazor Webassembly 下载的 .dll 文件?

c# - 无法将 DateTime 隐式转换为 Timespan

c# - 上午/下午到时间跨度

c# - 将许多 TimeSpans 减少为更少的平均 TimeSpans 的干净方法?