c# 的迭代器模式是通过 IEnumerator 和 IEnumerable 接口来实现的
c# 实现迭代器示例
public class CharList : IEnumerable { public string TargetStr { get; set; } public CharList(string str) { this.TargetStr = str; } /// <summary> /// 获取迭代器 /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { return new CharIterator(this.TargetStr); } } /// <summary> /// 实现IEnumerator接口 /// </summary> public class CharIterator : IEnumerator { //引用要遍历的字符串 public string TargetStr { get; set; } //指出当前遍历的位置 public int position { get; set; } public CharIterator(string targetStr) { this.TargetStr = targetStr; this.position = this.TargetStr.Length; } public object Current { get { if (this.position == -1 || this.position == this.TargetStr.Length) { throw new InvalidOperationException(); } return this.TargetStr[this.position]; } } public bool MoveNext() { //如果满足继续遍历的条件,设置position的值 if (this.position != -1) { this.position--; } return this.position > -1; } public void Reset() { this.position = this.TargetStr.Length; } }
语法糖模式:
public class StringList : IEnumerable { public string[] Count = new string[] { "1", "2", "3" }; public IEnumerator GetEnumerator() { for (int i = 0; i < Count.Length; i++) { yield return Count[i]; } } } 调用: var arr = new StringList(); foreach (string item in arr) { Console.Write(item); }
标签:string,迭代,C#,TargetStr,position,IEnumerator,public From: https://www.cnblogs.com/ZGXF/p/17397409.html