了解IEquatable [英] Understanding IEquatable
问题描述
如果我想比较对象,他们实现了IEquatable<>界面,我有几个问题:
- 为什么我必须重载Equals(对象),如果我要机具等于<>
- 我可以使用==和!=一旦我实现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:
- Why do i have to override Equals(object ) if i have to implements Equals<>
- 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 ofObject::Equals(Object)
andGetHashCode()
so that their behavior is consistent with that of theIEquatable<T>::Equals
method. If you do overrideObject::Equals(Object)
, your overridden implementation is also called in calls to the staticEquals(System.Object, System.Object)
method on your class. This ensures that all invocations of theEquals()
method return consistent results.2) No, these do plain reference comparisons and do not use the Equals method.
这篇关于了解IEquatable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!