该计划正与此实现:
class Instrument
{
public string ClassCode { get; set; }
public string Ticker { get; set; }
public override string ToString()
{
return " ClassCode: " + ClassCode + " Ticker: " + Ticker + '.';
}
}
但是,因为我需要使用仪器的意思我已经决定要实现equals /散列code:
But because I need to use Instrument in Dictionary I've decided to implement 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;
}
}
现在该方案已停止工作。在这样的或类似的地方,我收到KeyNotFoundException:
Now the program has stopped working. In such or similar places I receive "KeyNotFoundException":
if (cache.Keys.Any(instrument => instrument.Ticker == newTicker && instrument.ClassCode == newClassCode))
有没有可能是一些作品的code假设等于和哈希code不是执行? 或者,也许我只是实现他们是错的?对不起,我不熟悉C#等高级特性的最后一块code,不知道它是如何与equals或散列code连接。
Is it possible that some pieces of the code assume that equals and hashcode IS NOT implemented? Or probably I just implemented them wrong? Sorry I'm not familiar with such advanced features in C# as the last piece of code and don't know how it is connected with equals or hashCode.
您哈希code和equals方法应该只依赖的一成不变的特性 - 你实现使用类code和北京时间两个都具有setter方法,因此不能改变的。
Your HashCode and Equals methods should depend only on immutable properties - your implementation uses ClassCode and Ticker which both have setters and are therefore mutable.