迭代器(iterator)有时又称游标(cursor)是程序设计的软件设计模式,可在容器(container,例如链表或阵列)上遍访的接口,设计人员无需关心容器的内容。
简单迭代器的实现:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static bool delay = true;
static void Main(string[] args)
{
var result = getResult();
Console.WriteLine("first writeline : ");
//for循环控制迭代
/* for (var i = result.Current; result.MoveNext(); )
{
i = result.Current;
Console.WriteLine("outside writeLine : {0}", i);
}*/
//手动控制迭代
var i = result.Current;
Console.WriteLine("outside writeLine : {0}", i);
result.MoveNext();
i = result.Current;
Console.WriteLine("outside writeLine : {0}", i);
result.MoveNext();
i = result.Current;
Console.WriteLine("outside writeLine : {0}", i);
result.MoveNext();
i = result.Current;
Console.WriteLine("outside writeLine : {0}", i);
result.MoveNext();
i = result.Current;
Console.WriteLine("outside writeLine : {0}", i);
result.MoveNext();
i = result.Current;
Console.WriteLine("outside writeLine : {0}", i);
result.MoveNext();
i = result.Current;
Console.WriteLine("outside writeLine : {0}", i);
result.MoveNext();
i = result.Current;
Console.WriteLine("outside writeLine : {0}", i);
result.MoveNext();
i = result.Current;
Console.WriteLine("outside writeLine : {0}", i);
Console.ReadLine();
}
static IEnumerator getResult()
{
//var arr = Array.CreateInstance(typeof(Program), 1);
var arr = new int[] { 1, 2, 3, 45, 23, 23, 4, 3213 };
foreach (var item in arr)
{
yield return item;
if (delay) Thread.Sleep(100);
}
}
}
}