using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace demo4
{
public class Garage : IEnumerable
{
Car[] carArrary=new Car[4];
public Garage()
{
carArrary[0] = new Car("a",100);
carArrary[1] = new Car("b", 200);
carArrary[2] = new Car("c", 300);
carArrary[3] = new Car("d", 400);
}
public IEnumerator GetEnumerator()
{
return this.carArrary.GetEnumerator();//返回本类的一个IEnumerator的遍历对象
}
}
public class Car
{
public string name;
public int Speed;
public Car(string name,int Speed)
{
this.name = name;
this.Speed = Speed;
}
}
}
using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace demo4
{
class Program
{
static void Main(string[] args)
{
Garage a = new Garage();
foreach(Car b in a)
{
Console.WriteLine("{0} is going {1} MPH", b.name, b.Speed);
}
Console.WriteLine("GetEnumerator被定义为公开的,对象用户可以与IEnumerator类型交互,下面的结果与上面是一致的");
IEnumerator i = a.GetEnumerator();
while (i.MoveNext())
{
Car myCar = (Car)i.Current;
Console.WriteLine("{0} is going {1} MPH", myCar.name, myCar.Speed);
}
Console.ReadLine();
Console.ReadKey();
}
}
}
|