Overriding GetHashCode in VB without checked/unchecked keyword support?

前端 未结 7 1828
庸人自扰
庸人自扰 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:31

    Here is an implementation combining Hans Passant's answer and Jon Skeet's answer.

    It works even for millions of properties (i.e. no integer overflow exceptions) and is very fast (less than 20 ms to generate hash code for a class with 1,000,000 fields and barely measurable for a class with only 100 fields).

    Here is the structure to handle the overflows:

    
    Private Structure HashCodeNoOverflow
         Public Int64 As Int64
         Public Int32 As Int32
    End Structure
    

    And a simple GetHashCode function:

    Public Overrides Function GetHashCode() As Integer
    
        Dim hashCode As HashCodeNoOverflow
    
        hashCode.Int64 = 17
    
        hashCode.Int64 = CLng(hashCode.Int32) * 23 + Field1.GetHashCode
        hashCode.Int64 = CLng(hashCode.Int32) * 23 + Field2.GetHashCode
        hashCode.Int64 = CLng(hashCode.Int32) * 23 + Field3.GetHashCode
    
        Return hashCode.Int32
    
    End Function
    

    Or if your prefer:

    Public Overrides Function GetHashCode() As Integer
    
        Dim hashCode = New HashCodeNoOverflow With {.Int32 = 17}
    
        For Each field In Fields
            hashCode.Int64 = CLng(hashCode.Int32) * 23 + field.GetHashCode
        Next
    
        Return hashCode.Int32
    
    End Function
    

提交回复
热议问题