IComparable 和 IComparable 之间有什么区别? IEquatable接口?
这两个接口似乎都比较对象是否相等,那么它们之间的主要区别是什么?
Both the interfaces seem to compare objects for equality, so what are the major differences between them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
IEquatable
测试两个对象是否相等。IComparable
对正在比较的对象强加总排序。例如,
IEquatable
会告诉您 5 不等于 7。IComparable
会告诉您 5 在 7 之前。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.IEquatable
表示相等。IComparable
用于排序。IEquatable<T>
for equality.IComparable<T>
for ordering.除了 Greg D 的回答之外:
您可以实现
IComparable
而不实现IEquatable
对于一个类,其中部分排序有意义,并且您绝对希望消费者推断出这一点因为CompareTo()
返回零,这并不意味着对象是相等的(除了排序目的之外)。In addition to Greg D's answer:
You might implement
IComparable
without implementingIEquatable
for a class where a partial ordering makes sense, and where you very definitely want the consumer to infer that just becauseCompareTo()
returns zero, this does not imply that the objects are equal (for anything other than sorting purposes).正如 IEquatable 的 MSDN 页面 中所述:
等于
与CompareTo
As stated on the MSDN Page for IEquatable:
Equals
vs.CompareTo
IComparable
定义了一种特定于类型的比较方法,可用于对对象进行排序或排序。IEquatable
定义了可用于实现确定相等性的通用方法。假设您有 Person 类,
要对这些对象进行排序,您可以使用
people.Sort();
。但这会抛出异常。
框架不知道如何对这些对象进行排序。您需要告诉如何排序实现
IComparable
接口。这将使用
Sort()
方法对数组进行正确排序。接下来要比较两个对象,您可以使用
Equals()
方法。这将返回
false
,因为Equals
方法不知道如何比较两个对象。因此,您需要实现 IEquatable 接口并告诉框架如何进行比较。扩展前面的示例,它看起来像这样。IComparable <T>
defines a type specific comparison method which can be used to order or sort objects.IEquatable <T>
defines a generalized method which can be used to implement for determining equality.Let's say you have Person class
To sort these objects you can use
people.Sort();
.But this will thrown an an exception.
Framework doesn't know how to sort these objects. You need to tell how to sort implementing
IComparable
interface.This will sort the array properly with
Sort()
method.Next to compare two objects you can use
Equals()
method.This will return
false
becauseEquals
method doesn't know how to compare two objects. Therefore you need to implementIEquatable
interface and tell the framework how to do the comparison. Extending on the previous example it'll look like this.