比较DateTimes:DateTime.Compare()和关系运算符 [英] Comparing DateTimes: DateTime.Compare() versus relational operators

查看:135
本文介绍了比较DateTimes:DateTime.Compare()和关系运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有两种比较两个DateTimes的方法:

Here are two ways of comparing two DateTimes:

DateTime now = DateTime.Now;
DateTime then = new DateTime(2008, 8, 1);

// Method 1
if (DateTime.Compare(then, now) < 0)
    // ...

// Method 2
if (then < now)
    // ...

.Compare 返回一个整数(-1,0,1),表示第一个实例是否早于第二个实例的相同或更晚。

.Compare returns an integer (-1,0,1) indicating whether the first instance is earlier than, the same as, or later than the second instance.

我的问题是,当我可以使用关系运算符时,为什么要使用 .Compare / code>,< = == > = > )?在我看来,使用 .Compare ,我需要使用关系运算符(至少在上面的例子中;或者我可以创建一个switch语句来检查案例-1,0

My question is, why would I use .Compare when I can use relational operators (<,<=,==,>=,>) directly? It seems to me, using .Compare, I need to employ relational operators anyway (at least in the above example; alternatively I could create a switch statement examining cases -1, 0 and 1).

什么情况下更喜欢或需要使用 DateTime.Compare()

What situations would prefer or require usage of DateTime.Compare()?

推荐答案

通常,类型上的 .Compare 方法用于排序,而不是用于排序直接比较。

Typically, the .Compare methods on types are used for Sorting, not for doing direct comparisons.

IComparable< T> 界面,当支持类型时,允许许多框架类正确地对集合进行排序(例如 List< T> / code>,例如)

The IComparable<T> interface, when supported on a type, allows many framework classes to sort collections correctly (such as List<T>.Sort, for example).

这就是说,如果你想能够在通用类或方法中进行比较,限制你的通用对于实现 IComparable IComparable< T> 的类型的参数将允许您使用。 ()用于在具体类型未知时进行比较。

That being said, if you want to be able to do a comparison within a generic class or method, restricting your generic arguments to types which implement IComparable or IComparable<T> will allow you to use .Compare() for comparisons when a concrete type is unknown.

这篇关于比较DateTimes:DateTime.Compare()和关系运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆