我有几个实体需要分别制作IEquatable(Of TEntity)。
我希望他们首先检查EntityId之间的相等性,然后如果两者都为零,则应检查其他属性,例如相同的联系人姓名,相同的电话号码等。
这是怎么做到的?
答案 0 :(得分:3)
改编自MSDN IEquatable:
Public Class Entity : Implements IEquatable(Of Entity)
Public Overloads Function Equals(other As Entity) As Boolean _
Implements IEquatable(Of Entity).Equals
If Me.Id = other.Id Then
Return Me.ContactName = other.ContactName AndAlso Me.PhoneNumber = other.PhoneNumber
Else
Return False
End If
End Function
Public Overrides Function Equals(obj As Object) As Boolean
If obj Is Nothing Then Return MyBase.Equals(obj)
If TypeOf obj Is Entity
Return Equals(DirectCast(obj, Entity))
Else
Return False
End If
End Function
Public Overrides Function GetHashCode() As Integer
Return Me.Id.GetHashCode() Xor Me.ContactName.GetHashCode() Xor Me.PhoneNumber.GetHashCode()
End Function
Public Shared Operator = (entity1 As Entity, entity2 As Entity) As Boolean
Return entity1.Equals(entity2)
End Operator
Public Shared Operator <> (entity1 As Entity, entity2 As Entity) As Boolean
Return Not entity1.Equals(entity2)
End Operator
End Class
注意:强>
GetHashCode
的实现很幼稚,如果您需要在生产环境中使用它,请阅读this SO问题的答案。