我會避免這樣做,只是因爲它會毫無意義地創建一串字符串 - 儘管Kosi2801關於簡化碰撞的觀點也很重要。 (我懷疑它不會實際上創造了許多衝突,由於場的性質,但是......)
我會去的「簡單易得的權利」的算法我以前used in this answer (感謝尋找它槍:) - 而這是在有效的Java上市,如你所說。在這種情況下,它將最終爲:
public int GetHashCode()
{
int hash = 17;
// Suitable nullity checks etc, of course :)
hash = hash * 23 + StreetAddress.GetHashCode();
hash = hash * 23 + RuralRoute.GetHashCode();
hash = hash * 23 + City.GetHashCode();
hash = hash * 23 + Province.GetHashCode();
hash = hash * 23 + Country.GetHashCode();
hash = hash * 23 + PostalCode.GetHashCode();
return hash;
}
這當然不是無效的。如果您使用C#3你可能要考慮的擴展方法:
public static int GetNullSafeHashCode<T>(this T value) where T : class
{
return value == null ? 1 : value.GetHashCode();
}
然後你可以使用:
public int GetHashCode()
{
int hash = 17;
// Suitable nullity checks etc, of course :)
hash = hash * 23 + StreetAddress.GetNullSafeHashCode();
hash = hash * 23 + RuralRoute.GetNullSafeHashCode();
hash = hash * 23 + City.GetNullSafeHashCode();
hash = hash * 23 + Province.GetNullSafeHashCode();
hash = hash * 23 + Country.GetNullSafeHashCode();
hash = hash * 23 + PostalCode.GetNullSafeHashCode();
return hash;
}
您可以創建參數數組方法工具來使這個更簡單:
public static int GetHashCode(params object[] values)
{
int hash = 17;
foreach (object value in values)
{
hash = hash * 23 + value.GetNullSafeHashCode();
}
return hash;
}
,並稱之爲:
public int GetHashCode()
{
return HashHelpers.GetHashCode(StreetAddress, RuralRoute, City,
Province, Country, PostalCode);
}
在大多數類型有涉及原語,讓本來有些不必要的執行拳擊,但在這種情況下,你只需要引用。當然,你最終會不必要地創建一個數組,但你知道他們說的過早的優化是什麼?
供大家參考:http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-systemobjectgethashcode – lance 2009-06-05 19:16:20