标签:happy 实现 ble 开始 efault row 遍历 ring except
yield是C#为了简化遍历操作实现的语法糖,我们知道如果要要某个类型支持遍历就必须要实现系统接口IEnumerable,还需要实现IEnumerator,
static void Main(string[] args) { foreach (var item in new Program().SayHappyNewYear()) { Console.WriteLine(item); } MyList2 myList2 = new MyList2(); foreach (var item in myList2) { Console.WriteLine(item); } }
使用yield的写法
public IEnumerable<String> SayHappyNewYear() { yield return "恭"; // yield在这里充当隐式的IEnumerator接口 yield return "喜"; yield return "发"; yield return "财"; yield break; // 向迭代器发出结束迭代的信号 }
不使用yield,实现IEnumerable和IEnumerator的写法
class MyList2 : IEnumerable { public IEnumerator GetEnumerator() { IEnumerator tor = new MyEnumerator(0); return tor; } public class MyEnumerator : IEnumerator { private int state; private object current; public MyEnumerator(int state) { this.state = state; } public object Current { get { return current; } } public bool MoveNext() { switch (state) { case 0: current = "恭"; state = 1; return true; case 1: current = "喜"; state = 2; return true; case 2: current = "发"; state = 3; return true; case 3: current = "财"; state = 4; return true; case 4: return false; default: break; } return false; } public void Reset() { throw new NotImplementedException(); } } }
使用yield关键字后return 指定的对象后,当前位置会进行保存下来,下次调用的时候会从这个位置开始执行。
说白了,C#编译器会在编译后生成一个密封的类,该类实现了IEnumerator接口,所以是语法糖。
标签:happy 实现 ble 开始 efault row 遍历 ring except
原文地址:https://www.cnblogs.com/adspark/p/11804356.html