Comparing DateTimes: DateTime.Compare() versus relational operators

瘦欲@ 提交于 2019-12-08 14:34:07

问题


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()?


回答1:


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.




回答2:


When you're passing the object as an IComparable, the "relational" operators are not available. In this case, it can be handy.



来源:https://stackoverflow.com/questions/5625196/comparing-datetimes-datetime-compare-versus-relational-operators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!