用于迭代器的yield return

 在我们写迭代器的时候往往继承自IEnumerable

public class Tuple<T1, T2, T3> : Tuple<T1, T2>,IEnumerable
{
      T3 _t3;
    public Tuple(T1 t1, T2 t2, T3 t3) : base(t1, t2)     
    {
      this._t3 = t3;
    }
    //很方便的加入迭代功能
    public override IEnumerator GetEnumerator()
    {
      yield return this.Item_1;
      yield return this.Item_2;
      yield return this._t3;
    }
}

yield return相当于使用了一次MoveNext(),并返回Current的过程,所以上面的代码非常方便,

如果是一个数组的话

int[] arr=new int[]{1,2,3,4,5,6,7,8,9};

for(int i=0;i<arr.length;i++)

{

     yield return arr[i];

}

此时返回的就是arr[i]的值

原文地址:https://www.cnblogs.com/anbylau2130/p/3386337.html