Overriding GetHashCode in VB without checked/unchecked keyword support?

前端 未结 7 1835
庸人自扰
庸人自扰 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条回答
  •  Happy的楠姐
    2020-12-05 05:29

    Use Long to avoid the overflow:

    Dim hash As Long = 17
    '' etc..
    Return CInt(hash And &H7fffffffL)
    

    The And operator ensures no overflow exception is thrown. This however does lose one bit of "precision" in the computed hash code, the result is always positive. VB.NET has no built-in function to avoid it, but you can use a trick:

    Imports System.Runtime.InteropServices
    
    Module NoOverflows
        Public Function LongToInteger(ByVal value As Long) As Integer
            Dim cast As Caster
            cast.LongValue = value
            Return cast.IntValue
        End Function
    
         _
        Private Structure Caster
             Public LongValue As Long
             Public IntValue As Integer
        End Structure
    End Module
    

    Now you can write:

    Dim hash As Long = 17
    '' etc..
    Return NoOverflows.LongToInteger(hash)
    

提交回复
热议问题