简单迭代器的实现
例子1:
代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace test
{
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace test
{
//实现了IEnumerable接口,用于实现迭代
public class DaysOfTheWeek : IEnumerable
{
string[] m_Days = { "Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat" };
public class DaysOfTheWeek : IEnumerable
{
string[] m_Days = { "Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat" };
//实现了迭代的函数
public IEnumerator GetEnumerator()
{
for (int i = 0; i < m_Days.Length; i++)
{
yield return m_Days[i];
}
}
}
class TestDaysOfTheWeek
{
static void Main()
{
// Create an instance of the collection class
DaysOfTheWeek week = new DaysOfTheWeek();
// Iterate with foreach
foreach (string day in week)
{
System.Console.Write(day + " ");
}
}
}
}
{
for (int i = 0; i < m_Days.Length; i++)
{
yield return m_Days[i];
}
}
}
class TestDaysOfTheWeek
{
static void Main()
{
// Create an instance of the collection class
DaysOfTheWeek week = new DaysOfTheWeek();
// Iterate with foreach
foreach (string day in week)
{
System.Console.Write(day + " ");
}
}
}
}
例子2:
代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ForeachTest
{
public class Car
{
public string CarType;
public int CarYear;
public Car(string type,int year)
{
CarType = type;
CarYear = year;
}
}
public class Garage:IEnumerable
{
private Car[] CarArray = new Car[4];
public Garage()
{
CarArray[0] = new Car("Rusty", 30);
CarArray[1] = new Car("Clunker", 55);
CarArray[2] = new Car("Zippy", 30);
CarArray[3] = new Car("Fred", 30);
}
public IEnumerator GetEnumerator()
{
//return CarArray.GetEnumerator();
yield return CarArray[0];
yield return CarArray[1];
yield return CarArray[2];
yield return CarArray[3];
}
}
class Program
{
static void Main(string[] args)
{
Garage garage = new Garage();
foreach (Car car in garage)
{
Console.WriteLine("{0}---{1}",car.CarType,car.CarYear);
}
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ForeachTest
{
public class Car
{
public string CarType;
public int CarYear;
public Car(string type,int year)
{
CarType = type;
CarYear = year;
}
}
public class Garage:IEnumerable
{
private Car[] CarArray = new Car[4];
public Garage()
{
CarArray[0] = new Car("Rusty", 30);
CarArray[1] = new Car("Clunker", 55);
CarArray[2] = new Car("Zippy", 30);
CarArray[3] = new Car("Fred", 30);
}
public IEnumerator GetEnumerator()
{
//return CarArray.GetEnumerator();
yield return CarArray[0];
yield return CarArray[1];
yield return CarArray[2];
yield return CarArray[3];
}
}
class Program
{
static void Main(string[] args)
{
Garage garage = new Garage();
foreach (Car car in garage)
{
Console.WriteLine("{0}---{1}",car.CarType,car.CarYear);
}
}
}
}

浙公网安备 33010602011771号