【问题标题】:GetHashCode on null fields?空字段上的GetHashCode?
【发布时间】:2011-01-27 12:50:23
【问题描述】:

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

【问题讨论】:

标签: null nullreferenceexception equality gethashcode iequatable


【解决方案1】:

通常,如果字段为 null,则检查 null 并使用 0 作为哈希码的“部分”:

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

(请原谅 C# 主义,不确定 VB 中的 null 检查等效项)

【讨论】:

  • 关于'csism'的np。您刚刚澄清了 null 的哈希码是 0。
  • 顺便说一句,如果区分字段是 int,我可以返回 int 本身而不是它的哈希码吗?那会是个坏主意吗?即返回 ContactId ^ (Name == null ? 0 : Name.GetHashCode) (它是一个 int)?
  • 哈希码的唯一要求是相等的对象返回相等的哈希码。由于相等的 int 是相等的,因此将 int 作为其自己的哈希码返回就可以了。事实上,这正是 Int32.GetHashCode 似乎要做的事情......!
  • 异或不是组合哈希码的好方法。如需更稳健的方法,请参阅stackoverflow.com/questions/263400/…
  • 似乎 Nullable 在 HasValue 为 false 时已经返回 0:msdn.microsoft.com/en-us/library/axk9ks7d(v=vs.110).aspx
【解决方案2】:

正如 Jeff Yates 建议的那样,答案中的覆盖将为 (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;
}

What is the best algorithm for an overridden System.Object.GetHashCode?

【讨论】:

  • (Name == null ? 0 : Name.GetHashCode()) 在 C# 7 中可以压缩为 (Foo?.GetHashCode() ?? 0)
猜你喜欢
  • 2011-11-06
  • 2012-03-20
  • 1970-01-01
  • 2019-10-26
  • 1970-01-01
  • 1970-01-01
  • 2013-03-10
  • 2021-12-31
  • 2023-03-14
相关资源
最近更新 更多