了解IEquatable [英] Understanding IEquatable

查看:209
本文介绍了了解IEquatable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想比较对象,他们实现了IEquatable<>界面,我有几个问题:


  1. 为什么我必须重载Equals(对象),如果我要机具等于<>

  2. 我可以使用==和!=一旦我实现IEquatable?


解决方案

关于#1:


  

如果您实施 IEquatable< T> ,你也应该覆盖
  基础类实现
  对象::等于(对象)
   GetHash code(),使他们的行为是
  与的一致
   IEquatable< T> ::的Equals
  方法。如果你这样做覆盖
  对象::等于(对象),你
  重写的实现也是
  叫调用静态
  等于(System.Object的,System.Object的)
  方法在你的类。这可确保
  即所有调用的等于()
  方法返回一致的结果。


2)
不,这些纯做参考比较,并没有使用Equals方法。

If i want to compare objects and they implement the IEquatable<> interface, i have a few questions:

  1. Why do i have to override Equals(object ) if i have to implements Equals<>
  2. can i use == and != once i implement IEquatable ?

解决方案

Regarding #1:

From MSDN:

If you implement IEquatable<T>, you should also override the base class implementations of Object::Equals(Object) and GetHashCode() so that their behavior is consistent with that of the IEquatable<T>::Equals method. If you do override Object::Equals(Object), your overridden implementation is also called in calls to the static Equals(System.Object, System.Object) method on your class. This ensures that all invocations of the Equals() method return consistent results.

2) No, these do plain reference comparisons and do not use the Equals method.

这篇关于了解IEquatable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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