我在使用Dictionary ContainsKey方法时遇到问题。尽管我重写了Equals
和GetHashCode
方法,但我总是得到这个值。使用字典ContainKey总是返回true
我错过了什么?
FreeTime对象包含2个DateTime类型的变量(开始和结束)。
这里是满级
class FreeTime : IEquatable<FreeTime>
{
#region Constants
private const bool FirstDayOfWeekIsMonday = true;
#endregion
#region Private Variables
private DateTime start;
private DateTime end;
private static bool TodayIsSunday = (int)DateTime.Today.DayOfWeek == 0;
#endregion
#region Public Fields
public DateTime Start { get { return start; } }
public DateTime End { get { return end; } }
public void setStart(DateTime startValue) { start = startValue; }
public void setEnd(DateTime EndValue) { end = EndValue; }
#endregion
#region Constructor
public FreeTime()
{
start = DateTime.Today;
end = DateTime.Today;
}
public FreeTime(DateTime s,DateTime e)
{
start = s;
end = e;
}
#endregion
public enum PeriodType
{
SingleMonth,
AllMonths,
InterveningMonths
}
public bool Equals(FreeTime other)
{
////Check whether the compared object is null.
//if (Object.ReferenceEquals(other, null)) return false;
//Check wether the products' properties are equal.
return start.Equals(other.start) && end.Equals(other.end);
}
public override int GetHashCode()
{
//Get hash code for the start field if it is not null.
int hashStart = start == null ? 0 : start.GetHashCode();
//Get hash code for the end field.
int hashEnd = end.GetHashCode();
//Calculate the hash code .
return hashStart^hashEnd;
}
'
这是我如何使用containKey方法
Dictionary<FreeTime, string> FreeBusy = new Dictionary<FreeTime, string>();
if (FreeBusy.ContainsKey(intersection))
,但我总是geeting True值
你是否重载'Equals(object)'方法? – xanatos
您可以显示整个班级和一些示例数据吗? –
我推荐一下阅读:[什么是最好的算法重写系统对象gethashcode](http://stackoverflow.com/questions/263400/what-is-the-最佳算法覆盖系统对象gethashcode) –