What's the difference between IComparable & IE

2019-01-16 08:57发布

both the interfaces seem to compare objects for equality, so what's the major differences between them?

4条回答
The star\"
2楼-- · 2019-01-16 09:05

IEquatable<T> for equality.

IComparable<T> for ordering.

查看更多
SAY GOODBYE
3楼-- · 2019-01-16 09:16

As stated on the MSDN Page for IEquatable:

The IComparable interface defines the CompareTo method, which determines the sort order of instances of the implementing type. The IEquatable interface defines the Equals method, which determines the equality of instances of the implementing type.

Equals vs. CompareTo

查看更多
放我归山
4楼-- · 2019-01-16 09:23

In addition to Greg D's answer:

You might implement IComparable without implementing IEquatable for a class where a partial ordering makes sense, and where very definitely you wish the consumer to draw the inference that just because CompareTo() returns zero, this does not imply that the objects are equal (for anything other than sorting purposes).

查看更多
老娘就宠你
5楼-- · 2019-01-16 09:27

IEquatable tests whether two objects are equal.

IComparable imposes a total ordering on the objects being compared.

For example, IEquatable would tell you that 5 is not equal to 7. IComparable would tell you that 5 comes before 7.

查看更多
登录 后发表回答