空字段上的GetHashCode吗? [英] GetHashCode on null fields?
本文介绍了空字段上的GetHashCode吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我该如何处理 GetHashCode
函数中的空字段?
How do I deal with null fields in GetHashCode
function?
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,地址=空)。这些需要有所不同。正如链接中所建议的,类似于以下内容会更好。
As Jeff Yates suggested, the override in the answer would give the same hash for (name = null, address = "foo") as (name = "foo", address = null). These need to be different. As suggested in link, something similar to the following would be better.
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?
这篇关于空字段上的GetHashCode吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文