C#迭代器模式原理实现

这里的yield相当于SpecialEnumerator方法。

List<int> list =new List<int>{1,2,3,4,5};

foreach(var item in list){}

分析:List中实现了GetEnumerator()的迭代器方法,foreach语法糖执行了GetEnumerator().MoveNext()从而达到遍历数组的目标。那么为什么这里的item只能取值不能赋值呢,这个是因为List集合中的属性public object current {get;}没有set访问器,估计是出于集合的内存安全考虑。

原文地址:https://www.cnblogs.com/happyShare/p/14114004.html