啟用 Foreach
許多用戶希望能夠使用 foreach 遍歷我的列表。為此,我需要在類中實現 Ienumerable,并定義一個單獨的用于實現 Ienumerable 的類。第一步,測試:
[Test]
public void TestForeach()
{
IntegerList list = new IntegerList();
list.Add(5);
list.Add(10);
list.Add(15);
list.Add(20);ArrayList items = new ArrayList();foreach (int value in list)
{
items.Add(value);
}Assertion.AssertEquals("Count", 4, items.Count);
Assertion.AssertEquals("index 0", 5, items[0]);
Assertion.AssertEquals("index 1", 10, items[1]);
Assertion.AssertEquals("index 2", 15, items[2]);
Assertion.AssertEquals("index 3", 20, items[3]);
}我還通過 IntegerList 實現 IEnumerable:public IEnumerator GetEnumerator()
{
return null;
} 運行測試時,此代碼生成異常。為了正確地實現此功能,我將使用一個嵌套類作為枚舉器。 class IntegerListEnumerator: IEnumerator
{
IntegerList list;
int index = -1;public IntegerListEnumerator(IntegerList list)
{
this.list = list;
}
public bool MoveNext()
{
index++;
if (index == list.Count)
return(false);
else
return(true);
}
public object Current
{
get
{
return(list[index]);
}
}
public void Reset()
{
index = -1;
}
} 此類將一個指針傳遞給 IntegerList 對象,然后只返回此對象中的元素。 這樣,便可以對列表執行 foreach 操作,但遺憾的是 Current 屬性屬于對象類型,這意味著每個值將被裝箱才能將其返回。此問題可采用一種基于模式的方法加以解決,此方法酷似當前方法,但它通過 GetEnumerator() 返回一個真正的類(而非 IEnumerator),且此類中的 Current 屬性為 int 類型?! ∪欢鴪绦写瞬僮骱?,我要確保在不支持該模式的語言中仍然可以使用這種基于接口的方法。我將復制編寫的上一個測試并修改 foreach 以轉換為接口: foreach (int value in (IEnumerable) list) 只需少許改動,列表即可在兩種情況下正常運行。請查看代碼樣例以獲取更多細節和更多測試。 幾點說明
為本月的專欄文章編寫代碼和文字大約花了我一個小時的時間。事先編寫測試的優點就是您可以對在類中添加哪些內容以使測試通過有一個清楚的熟悉,從而簡化代碼的編寫。 假如要進行小型、遞增的測試,則使用此方法最合適。我鼓勵您在小型項目中使用此方法。事先測試開發是所謂的“靈敏方法”的一部分。進入討論組討論。