C# 迭代器和集合
將介紹迭代器如何用于迭代存儲(chǔ)在字典類型的集合中的對(duì)象,而不必處理Dictionaryltem對(duì)象。在DictionaiyAnimals文件夾中,可以找到接下來這個(gè)項(xiàng)目的代碼。下面是集合類Animals:
public class Animals : DictionaryBase
{
public void Add(string newID, Animal newAnimal) =>
Dictionary.Add(newID, newAnimal);
public void Remove(string animallD) =>
Dictionary.Remove(animallD);
public Animal this[string animallD]
{
get { return (Animal)Dictionary[animallD]; }
set { Dictionary [animallD] *= value; }
}
}
可在這段代碼中添加如下的簡(jiǎn)單迭代器,以便執(zhí)行預(yù)期的操作:
public new IEnumerator GetEnumerator <)
{
foreach (object animal in Dictionary.Values)
yield return (Animal)animal;
}
現(xiàn)在可使用下面的代碼來迭代集合中的Animal對(duì)象:
foreach (Animal myAnimal in animalCollection)
{
WriteLine($"New {myAnimal.ToString()} object added to 11 + $" custom collection, Name = {myAnimal - Name}");
}
點(diǎn)擊加載更多評(píng)論>>