gpt4 book ai didi

null - 空字段上的GetHashCode吗?

转载 作者:行者123 更新时间:2023-12-03 12:31:14 25 4
gpt4 key购买 nike

如何处理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

最佳答案

正如杰夫·耶茨(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?

关于null - 空字段上的GetHashCode吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2444748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com