首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >空字段上的GetHashCode?

空字段上的GetHashCode?
EN

Stack Overflow用户
提问于 2010-03-15 10:27:42
回答 2查看 16.9K关注 0票数 22

如何处理GetHashCode函数中的空字段?

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-01-31 05:39:44

正如Jeff Yates所建议的,答案中的覆盖将为(name = null,address = "foo")提供与(name = "foo",address = null)相同的散列。这些需要有所不同。正如link中所建议的,类似于下面的内容会更好。

代码语言:javascript
复制
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?

票数 13
EN

Stack Overflow用户

发布于 2010-03-15 10:38:14

通常,您检查null,如果字段为null,则使用0作为散列代码的“部分”:

代码语言:javascript
复制
return (Name == null ? 0 : Name.GetHashCode()) ^ 
  (Address == null ? 0 : Address.GetHashCode());

(请原谅C#-ism,不确定在VB中是否有null检查等效项)

票数 35
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2444748

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档