Подтвердить что ты не робот

GetHashCode в нулевых полях?

Как мне обрабатывать нулевые поля в функции 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
4b9b3361

Ответ 1

Как предположил Джефф Йейтс, переопределение в ответе даст такой же хеш для (name = null, address = "foo" ) как (name = "foo", address = null). Они должны быть разными. Как было предложено в ссылке, что-то похожее на следующее было бы лучше.

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;
}

Каков наилучший алгоритм для переопределенного System.Object.GetHashCode?

Ответ 2

Обычно вы проверяете значение null и используете 0 для этой "части" хеш-кода, если поле имеет значение null:

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

(pardon the С# -ism, не уверен в эквиваленте нулевой проверки в VB)