开发者

Cascading IEquatable(Of T)

开发者 https://www.devze.com 2022-12-23 08:11 出处:网络
I have several entities I开发者_如何学Go need to make IEquatable(Of TEntity) respectively. I want them first to check equality between EntityId, then if both are zero, should check regarding to other

I have several entities I开发者_如何学Go need to make IEquatable(Of TEntity) respectively.

I want them first to check equality between EntityId, then if both are zero, should check regarding to other properties, for example same contact names, same phone number etc.

How is this done?


Adapted from 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

Note:

The implementations of GetHashCode is naive and if you need to use this in a production environment, read the answers to this SO question.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号