Domanda

Come faccio a trattare con i campi nulli in funzione GetHashCode?

Module Module1
  Sub Main()
    Dim c As New Contact
    Dim hash = c.GetHashCode
  End Sub

  Public Class Contact : Implements IEquatable(Of Contact)
    Public Name As String
    Public Address As String

    Public Overloads Function Equals(ByVal other As Contact) As Boolean _
        Implements System.IEquatable(Of Contact).Equals
      Return Name = other.Name AndAlso Address = other.Address
    End Function

    Public Overrides Function Equals(ByVal obj As Object) As Boolean
      If ReferenceEquals(Me, obj) Then Return True

      If TypeOf obj Is Contact Then
        Return Equals(DirectCast(obj, Contact))
      Else
        Return False
      End If
    End Function

    Public Overrides Function GetHashCode() As Integer
      Return Name.GetHashCode Xor Address.GetHashCode
    End Function
  End Class
End Module
È stato utile?

Soluzione

Come suggerito Jeff Yates, l'override nella risposta darebbe lo stesso hash per (name = null, indirizzo = "foo") come (name = "foo", indirizzo = null). Questi devono essere diversi. Come suggerito in collegamento, qualcosa di simile al seguente sarebbe meglio.

public override int GetHashCode()
{
    unchecked // Overflow is fine, just wrap
    {
        int hash = 17;
        hash = hash * 23 + (Name == null ? 0 : Name.GetHashCode());
        hash = hash * 23 + (Address == null ? 0 : Address.GetHashCode());
    }
    return hash;
}

Qual è il miglior algoritmo per un System.Object.GetHashCode override?

Altri suggerimenti

In genere, si controlla nulla e utilizzare 0 per quella "parte" del codice hash se il campo è nullo:

return (Name == null ? 0 : Name.GetHashCode()) ^ 
  (Address == null ? 0 : Address.GetHashCode());

(pardon il C # -ismo, non è sicuro del controllo nullo equivalente in VB)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top