널 필드의 gethashcode?
-
20-09-2019 - |
문제
널 필드를 어떻게 처리합니까? 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, addr 이것들은 달라야합니다. Link에서 제안한 바와 같이, 다음과 비슷한 것이 더 나을 것입니다.
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;
}
다른 팁
일반적으로 필드가 NULL 인 경우 NULL을 확인하고 해시 코드의 "부품"에 0을 사용합니다.
return (Name == null ? 0 : Name.GetHashCode()) ^
(Address == null ? 0 : Address.GetHashCode());
(C#-ism을 용서해보십시오.
제휴하지 않습니다 StackOverflow