迭代器(iterator)提供一种方法顺序访问一个聚合对象的元素,而不暴露内部的标识,是可以在容器上遍历访问的接口
凡是可以用foreach遍历的类都实现了迭代器
用法:
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 迭代器
{
#region 标准迭代器的使用
//接口:IEnumerable, IEnumerator
//命名空间:using System.Collections;
class Test : IEnumerable, IEnumerator
{
private int[] list;
public int pos = -1;
public Test()
{
list = new int[] { 1, 2, 3, 4, 5 };
}
#region IEnumerable
public IEnumerator GetEnumerator()
{
Reset();
return this;
}
#endregion
#region IEnumerator
public object Current
{
get
{
return list[pos];
}
}
//获取下一光标
public bool MoveNext()
{
pos++;
return pos < list.Length;
}
//重置光标位置,一般写在GetEnumerator方法中
public void Reset()
{
pos = -1;
}
#endregion
}
#endregion
#region 用yield return语法糖实现迭代器
//主要作用将复杂代码简单化
//实现接口IEnumerable
class list2 : IEnumerable
{
private int[] list;
public list2()
{
list = new int[] { 1, 2, 3, 4, 5 ,6};
}
public IEnumerator GetEnumerator()
{
for(int i=0;i<list.Length;i++)
{
//yield理解为暂时返回,保留当前状态
//yield里面系统还是会调用MoveNext那些方法,我们不用写罢了,原理一样
yield return list[i];
}
}
}
#endregion
class Program
{
static void Main(string[] args)
{
Test t = new Test();
//foreach的本质
//1.先获取in后面这个对象的IEnumerable调用GetEnumerator(),不继承IEnumerable也可以
//2.执行得到IEnumerator对象调用其MoveNext方法
//3.只有MoveNext返回为true,就回去得到Current,然后复制给item
foreach (int item in t)
{
Console.WriteLine(item);
}
list2 l2 = new list2();
foreach (int item in l2)
{
Console.WriteLine(item);
}
}
}
}