除了foreach 另外一种方式遍历
private static void TestForeach1()
{
List<int> ls = new List<int>();
for (int i = 0; i < 10; i++)
{
ls.Add(i);
}
//进行遍历
Console.WriteLine("常规遍历");
foreach (var item in ls)
{
Console.WriteLine(item);
}
Console.WriteLine("另一种遍历方式");
IEnumerator<int> numberIntEnumerator = ls.GetEnumerator();
while (numberIntEnumerator.MoveNext())
{
var currentInt = numberIntEnumerator.Current;
Console.WriteLine(currentInt);
}
}
从上面的例子中我们能够看到 foreach 一些本质, 它包含了一个 Enumerator 类
怎么让自己类 实现能被foreach 遍历呢?
model 实体
public class PeopleLoping
{
public string Name { get; set; }
public string Address { get; set; }
}
集合要实现 IEnumerable 接口 这个是基本。
两种方式实现 Enumerator 方式,一种是自己实现,另外一种使用语法糖 来让编译器帮你生成
public class PeopleSet : IEnumerable
{
private List<PeopleLoping> enumerableLs = new List<PeopleLoping>();
#region
public IEnumerator GetEnumerator()
{
for (int i = 0; i < enumerableLs.Count; i++)
{
// 编译器帮你生成 Enumerator 类
yield return enumerableLs[i];
}
}
#endregion
// 自己实现 Enumerator 类方法
//public IEnumerator GetEnumerator()
//{
// return new PeopleEnumerator(enumerableLs);
//}
public void Add(PeopleLoping p)
{
this.enumerableLs.Add(p);
}
//弄成内部类 免得污染类空间
class PeopleEnumerator : IEnumerator
{
public List<PeopleLoping> Peoples = new List<PeopleLoping>();
private int idx = -1;
public PeopleEnumerator(List<PeopleLoping> PeopleLs)
{
this.Peoples = PeopleLs;
}
public bool MoveNext()
{
idx++;
return Peoples.Count > idx;
}
public void Reset()
{
idx = -1;
}
public object Current => Peoples[idx];
}
}
以上即是,自己的理解 C# 提供的迭代器模式。