我的問題是ContainsKey總是返回false,即使他們的鍵已被添加和.Equals計算結果爲true。C#字典ContainsKey
我有下面的類:然後有一個字典,看起來像這樣
public class StatisticsFilter
{
private String someString1;
private String someString2;
.....
public override string ToString()
{
return string.Format("{0}-{1}-{2}-{3}-{4}", someString1, someString2, ...)
}
public override bool Equals(object obj)
{
return obj.ToString().Equals(ToString());
}
public override int GetHashCode()
{
return ToString().GetHashCode();
}
}
我:
private readonly IDictionary<StatisticsFilter, Statistics> _filteredStatisticsDict =
new Dictionary<StatisticsFilter, Statistics>();
....
{
// ALWAYS EVALUATES TO FALSE!
if (_filteredStatisticsDict.ContainsKey(statisticsFilter) == false)
{
_filteredStatisticsDict.Add(statisticsFilter, new Statistics());
}
}
問題肯定在於你的'GetHashCode'。它是否總是爲相同的實例返回相同的值? – 2011-05-25 19:07:45
你是否通過了課程的關鍵或實例? – MBen 2011-05-25 19:15:37
等待,'ContainsKey(statisticsFilter)'評估爲false,或'ContainsKey(statisticsFilter)== false'評估爲false? – 2011-05-25 19:20:04