Overriding GetHashCode in VB without checked/unchecked keyword support?

前端 未结 7 1848
庸人自扰
庸人自扰 2020-12-05 05:00

So I\'m trying to figure out how to correctly override GetHashCode() in VB for a large number of custom objects. A bit of searching leads me to this wonderful

7条回答
  •  情书的邮戳
    2020-12-05 05:19

    Improved answer Overriding GetHashCode in VB without checked/unchecked keyword support?

    Public Overrides Function GetHashCode() as Integer
      Dim hashCode as Long = 0
      If myReplacePattern IsNot Nothing Then _
        hashCode = ((hashCode*397) Xor myField.GetHashCode()) And &HffffffffL
      If myPattern IsNot Nothing Then _
        hashCode = ((hashCode*397) Xor myOtherField.GetHashCode()) And &HffffffffL
      Return CInt(hashCode)
    End Function
    

    There is a trimming after each multiplication. And literal is defined explicitly as Long because the And operator with an Integer argument does not zeroize the upper bytes.

提交回复
热议问题