我已经为我的类创建了一个IEqualityComparer来表示来自数据库的对象,我想要覆盖这些类的Equals方法,以便在调用Equals,Contains等时比较对象的Id。问题是我的从不调用Equals函数,任何人都可以看到为什么测试总会返回false?
谢谢!
DatabaseEntityEqualityComparer.vb
Imports System.Collections.Generic
Public Class DatabaseEntityEqualityComparer
Implements IEqualityComparer(Of IDatabaseEntity)
Public Overloads Function Equals(x As IDatabaseEntity, y As IDatabaseEntity) As Boolean Implements IEqualityComparer(Of IDatabaseEntity).Equals
'check whether the compared objects reference the same data
If x Is y Then Return True
'check whether any of the compared objects is null
If x Is Nothing OrElse y Is Nothing Then Return False
'check whether the IDatabaseEntity properties are equal, and are of the same type
Return (x.Id = y.Id) AndAlso (x.GetType() = y.GetType())
End Function
Public Overloads Function GetHashCode(obj As IDatabaseEntity) As Integer Implements IEqualityComparer(Of IDatabaseEntity).GetHashCode
If obj Is Nothing Then
Return 0
End If
Return obj.Id.ToString().GetHashCode()
End Function
End Class
IDatabaseEntity.vb
Public Interface IDatabaseEntity
Property Id As Integer
End Interface
Person.vb
Public Class Person
Implements IDatabaseEntity
Public Property Id As Integer Implements IDatabaseEntity.Id
End Class
运行测试
Dim p1 As New Person()
p1.Id = 1
Dim p2 As New Person()
p2.Id = 1
If p1.Equals(p2) Then
Response.Write("Equals")
Else
Response.Write("Not Equals")
End If
Response.End()
答案 0 :(得分:2)
IEqualityComparer
是一个允许创建自定义euqality比较器的接口。例如,您可以在许多LINQ方法中使用它,例如Intersect
,Except
,GroupBy
,Join
等。但您必须将比较器的实例传递给这些方法。
如果您想要一般更改覆盖Equals
和GetHashCode
:
Public Class Person
Implements IDatabaseEntity
Public Property Id As Integer Implements IDatabaseEntity.Id
Public Overrides Function Equals(obj As Object) As Boolean
If obj Is Nothing Then Return False
If Object.ReferenceEquals(Me, obj) Then Return True
Dim Person2 As Person = TryCast(obj, Person)
If Person2 Is Nothing Then Return False
Return Person2.Id = Id
End Function
Public Overrides Function GetHashCode() As Integer
Return Id
End Function
End Class
如果您想使用比较器,可以这样使用Equals
:
Dim comparer = New DatabaseEntityEqualityComparer()
If comparer.Equals(p1, p2) Then
Response.Write("Equals")
End If