Eviterei di farlo semplicemente perché crea una serie di stringhe inutilmente - anche se il punto di vista di Kosi2801 sul rendere semplici le collisioni è anche rilevante. (Ho il sospetto che non sarebbe in realtà creare molte collisioni, a causa della natura dei campi, ma ...)
vorrei andare per il "semplice e facile da ottenere" algoritmo ho già used in this answer (grazie per la ricerca di lance :) - e che è elencato in Java efficace, come hai detto tu. In questo caso si finirebbe come:
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;
}
Ovviamente non è sicuro. Se stai usando C# 3 si potrebbe prendere in considerazione un metodo di estensione:
public static int GetNullSafeHashCode<T>(this T value) where T : class
{
return value == null ? 1 : value.GetHashCode();
}
quindi è possibile utilizzare:
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;
}
È potrebbe creare un programma di utilità metodo di matrice di parametri per rendere questo ancora più semplice :
public static int GetHashCode(params object[] values)
{
int hash = 17;
foreach (object value in values)
{
hash = hash * 23 + value.GetNullSafeHashCode();
}
return hash;
}
e chiamarlo con:
public int GetHashCode()
{
return HashHelpers.GetHashCode(StreetAddress, RuralRoute, City,
Province, Country, PostalCode);
}
Nella maggior parte dei tipi ci sono le primitive coinvolte, in modo da eseguire la boxe un po 'inutilmente, ma in questo caso avresti solo riferimenti. Naturalmente, ci si finisce per creare una matrice inutilmente, ma sai quello che dicono di ottimizzazione prematura ...
Per la vostra considerazione: non http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-systemobjectgethashcode – lance