¿He implementado Equals () / GetHashCode () correctamente?
El programa estaba trabajando con esta implementación:
class Instrument
{
public string ClassCode { get; set; }
public string Ticker { get; set; }
public override string ToString()
{
return " ClassCode: " + ClassCode + " Ticker: " + Ticker + '.';
}
}
Pero porque necesito usar Instrument in Dictionary he decidido implementar equals / hashcode:
class Instrument
{
public string ClassCode { get; set; }
public string Ticker { get; set; }
public override string ToString()
{
return " ClassCode: " + ClassCode + " Ticker: " + Ticker + '.';
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
Instrument instrument = obj as Instrument;
if (instrument == null)
return false;
return ((ClassCode.Equals(instrument.ClassCode)) && (Ticker.Equals(instrument.Ticker));
}
public override int GetHashCode()
{
int hash = 13;
hash = (hash * 7) + ClassCode.GetHashCode();
hash = (hash * 7) + Ticker.GetHashCode();
return hash;
}
}
Ahora el programa ha dejado de funcionar. En lugares similares o similares, recibo "KeyNotFoundException":
if (cache.Keys.Any(instrument => instrument.Ticker == newTicker && instrument.ClassCode == newClassCode))
¿Es posible que algunas partes del código asuman que igual y hashcode NO ESTÁ implementado? ¿O probablemente simplemente los implementé mal? Lo siento, no estoy familiarizado con funciones tan avanzadas en C # como el último fragmento de código y no sé cómo está conectado con equals o hashCode.