我在使用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) –