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

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

问题描述

下面是比较两个DateTime是否两种方式:

 现在的DateTime = DateTime.Now; 
的DateTime然后=新日期时间(2008年8,1);

//方法1
如果(DateTime.Compare(当时,现)小于0)
// ...

//方法2
如果(当时<现在)
// ...

.Compare 返回指示一审是否比以前的相同或晚于第二个实例的一个整数(-1,0,1)。



我的问题是,我为什么要使用 .Compare 时,我可以使用关系运算符(< < = == > = > )直接?在我看来,使用 .Compare ,我需要使用关系运算符呢(至少在上面的例子中,我也可以创建一个switch语句的案件进行审查-1,0 1)。



什么情况下,宁愿或者要求 DateTime.Compare的使用()


解决方案

通常,用于排序,而不是做对类型 .Compare 方法

直接比较。



IComparable的< T> 接口,支持一个类型时,让很多框架类的集合正确排序(如列表< T>的.sort ,例如)。



这是说,如果你希望能够做一个泛型类或方法中的一个比较,限制您的泛型参数到实现类型 IComparable的 IComparable的< T> 将允许您使用 .Compare()因为当一个具体类型是未知的比较。


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 returns an integer (-1,0,1) indicating whether the first instance is earlier than, the same as, or later than the second instance.

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).

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

解决方案

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

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

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.

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

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