How can we check reference equality for a type that implements equality operator?

廉价感情. 提交于 2019-12-02 09:54:04

If you mean equality by reference, you may use the Object.ReferenceEquals static method even if the == operator was overloaded for the current type to work otherwise:

Object.ReferenceEquals(obj1, obj2);

What does object "object equality"?

If by "how can we check object equality for a type that implements equality operator?", you actually mean "how can we check object equality for a type that implements IEquatable<T>", the short answer is...however you want (with some caveats).

The documentation for IEquatable<T> offers some guidelines. You might also want to implement IComparable<T> as well. And if you implement both IEquatable<T> and IComparable<T>, it would make sense if your Equals() method returns true for all the cases where your CompareTo() method returns 0, and for your Equals() method to return false for all the cases where your CompareTo() method returns a non-zero value.

Further, you might want to ensure that you properly override == and != to provide the same behaviour as calling Equals().

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