private int compare_Click(object sender, System.EventArgs e)
{
int diff = dateCompare(first.Value, second.Value);
info.Text = "";
show("first == second", diff == 0);
show("first != second", diff != 0);
show("first < second", diff < 0);
show("first <= second", diff <= 0);
show("first > second", diff > 0);
show("first >= second", diff >= 0);
}
單擊窗體上的Compare按鈕,就會執行這個方法。該方法獲取窗體上的first和second這兩個DateTimePicker控件中顯示的日期值,並調用另一個名為dateCompare的方法來比較它們。我們將在下一個步驟中具體討論dateCompare方法,這裡只是簡單地說一下。該方法的作用是比較它的兩個參數值,並根據比較結果來返回一個整數值。如果兩個值相同,就返回零;如果first的值小於second的值,就返回-1;如果first的值大於second的值,就返回+1(假如一個日期在日歷上排在另一個日期的後面,就說前者大於後者)。
show方法用於在窗體上的info文本框控件中顯示比較結果。
7. 找到dateCompare方法,如下所示:
private int dateCompare(DateTime leftHandSide, DateTime rightHandSide)
{
// TO DO
return 42;
}
該方法目前在調用後始終返回同一個值,而不是通過比較參數值來返回0,-1或+1。這解釋了為什麼應用程序不像我們期望的那樣工作!現在,需要實現這個方法,讓它正確地比較兩個日期。
8. 從dateCompare方法中移除// TO DO注釋和return語句。
9. 在dateCompare方法主體中輸入以下語句:
int result;
if (leftHandSide.Year < rightHandSide.Year)
result = -1;
else if (leftHandSide.Year > rightHandSide.Year)
result = +1;
else if (leftHandSide.Month < rightHandSide.Month)
result = -1;
else if (leftHandSide.Month > rightHandSide.Month)
result = +1;
else if (leftHandSide.Day < rightHandSide.Day)
result = -1;
else if (leftHandSide.Day > rightHandSide.Day)
result = +1;
else
result = 0;
return result;
假如leftHandSide.Year < rightHandSide.Year和leftHandSide.Year > rightHandSide.Year為false,那麼leftHandSide.Year == rightHandSide.Year肯定為true,程序流程將正確轉移,開始比較lhs和rhs的Month屬性。類似地,假如leftHandSide.Month < rightHandSide.Month和leftHandSide.Month > rightHandSide.Month為false,那麼leftHandSide.Month == rightHandSide.Month肯定為true,程序將開始比較lhs和rhs的Day屬性。最後,假如leftHandSide.Day < rightHandSide.Day和leftHandSide.Day > rightHandSide.Day為false,那麼leftHandSide.Day == rightHandSide.Day肯定為true;另外,由於在這時候,Month和Year屬性也肯定為true,所以兩個日期肯定是相同的。