当我们已经拥有Object.Equals时,为什么我们有IComparable对象 [英] Why we have IComparable object when we already have Object.Equals

查看:123
本文介绍了当我们已经拥有Object.Equals时,为什么我们有IComparable对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们已经有Object.Equals方法时,为什么我们需要IComparable接口。

因为Icomparable给我们CompareTo()方法,它与Object.Equals具有相同的实现。



非常感谢你。

Why we need IComparable interface when we already have Object.Equals method.
As Icomparable gives us CompareTo() method which has same implementation as Object.Equals.

Thanks you very much.

推荐答案

扩展基督徒...



Object.Equals测试两个引用是否如果对象是引用类型,则等于(不相等)。如果对象是值类型,则测试是否相等。



Object.Equals的文档 [ ^ ]给出了一个很好的例子。



可比较的 [ ^ ]用于确保对象与其他对象(大于,小于或等于)相当。这些对于引用类型非常有用,例如,如果您创建了一个纬度或经度类型,可以将字符串或十进制数与对象进行比较以获得相等。
Expanding on Christian...

Object.Equals tests if two references are equal (not equality) if the objects are reference types. If the objects are value types, it tests for equality.

The documentation for Object.Equals[^] gives a good example of the difference.

IComparable[^] is used to ensure that an object is comparable to other objects (greater than, less than, or equal to). These can be useful for reference types, for example if you created an Latitude or Longitude type that could compare either a string or decimal number against the object for equality.


接口为您提供了一个共同点与其他不同对象一起工作的方法。如果一个对象影响了这个接口,它可以被使用这个接口的方法使用。
An interface gives you a common way to work with otherwise different objects. If an object impliments this interface, it can be used by methods that work with this interface.


我认为这可以帮助你:

一个接口给你一个与其他不同对象一起工作的常用方法。如果一个对象涉及该接口,则可以使用与该接口一起使用的方法。
I think this may help YOU:
An interface gives you a common way to work with otherwise different objects. If an object impliments this interface, it can be used by methods that work with this interface.


这篇关于当我们已经拥有Object.Equals时,为什么我们有IComparable对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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