我正在尝试使用以下示例来理解枚举器
public class Garage : IEnumerable
{
private Car[] cars = new Car[4];
public Garage()
{
cars[0] = new Car() { Id = Guid.NewGuid(), Name = "Mazda 3", CurrentSpeed = 90 };
cars[1] = new Car() { Id = Guid.NewGuid(), Name = "Mazda 6", CurrentSpeed = 80 };
}
public IEnumerator GetEnumerator()
{
// return the array object's IEnumerator
return cars.GetEnumerator();
}
}
static void Main(string[] args)
{
IEnumerator i = cars.GetEnumerator();
i.MoveNext();
Car myCar = (Car)i.Current;
Console.WriteLine("{0} is going {1} km/h", myCar.Name, myCar.CurrentSpeed);
Console.ReadLine();
}
如何在不使用 foreach 循环的情况下在控制台第二辆车上显示?