equality in c#

  1. 单个参数的equals 是Object类的虚方法可以在子类中实现override,如果要override,可以调用第三点接口里的具体类型的Equals, 如果不override, 则 a call to the Equals(Object) method is equivalent to a call to the ReferenceEquals method.
  2. 两个参数的equals()是个静态工具方法,被有需要的人调用(比如operator override的实现就可以用它)。它的逻辑是先看reference equal, 不行再调用单个参数的equals。这是固定的逻辑,不会被改变。
  3. IEquatable<T>是类型具体的相等,和第一点不同的是不是object,而是具体类型。用途: The IEquatable<T> interface is used by generic collection objects such as Dictionary<TKey,TValue>List<T>, and LinkedList<T> when testing for equality in such methods as ContainsIndexOfLastIndexOf, and Remove. It should be implemented for any object that might be stored in a generic collection.
  4. GetHashCode()也是Object类的虚方法, 用于: A hash code is a numeric value that is used to insert and identify an object in a hash-based collection such as the Dictionary<TKey,TValue> class, the Hashtable class, or a type derived from the DictionaryBase class. The GetHashCode method provides this hash code for algorithms that need quick checks of object equality.

所以比较的实现主要看需要在那些地方比,这些都可以(有可能需要)实现。virtual equals(Ojbect类型的虚方法)和 operator override不和具体的泛型集合类相关,如果自己的代码用泛型集合类,没有直接使用它们,也可以不实现。

发表回复