内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我如何处理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,则检查NULL,并对哈希代码的“部分”使用0:
return (Name == null ? 0 : Name.GetHashCode()) ^ (Address == null ? 0 : Address.GetHashCode());