C# 迭代器模式
1 public class Swimers : IEnumerable 2 { 3 // Methods 4 public IEnumerator GetEnumerator() 5 { 6 Program.Swimers iteratorVariable0 = new Program.Swimers { 7 Name = "LBJ" 8 }; 9 yield return iteratorVariable0; 10 Program.Swimers iteratorVariable1 = new Program.Swimers { 11 Name = "KB" 12 }; 13 yield return iteratorVariable1; 14 Program.Swimers iteratorVariable2 = new Program.Swimers { 15 Name = "KB1" 16 }; 17 yield return iteratorVariable2; 18 Program.Swimers iteratorVariable3 = new Program.Swimers { 19 Name = "KB1" 20 }; 21 yield return iteratorVariable3; 22 } 23 24 public override string ToString() 25 { 26 return ("Name:" + this.Name); 27 } 28 29 // Properties 30 public int Age { get; set; } 31 32 public string Club { get; set; } 33 34 public string Name { get; set; } 35 36 // Nested Types 37 [CompilerGenerated] 38 private sealed class <GetEnumerator>d__4 : IEnumerator<object>, IEnumerator, IDisposable 39 { 40 // Fields 41 private int <>1__state; 42 private object <>2__current; 43 public Program.Swimers <>4__this; 44 public Program.Swimers <>g__initLocal0; 45 public Program.Swimers <>g__initLocal1; 46 public Program.Swimers <>g__initLocal2; 47 public Program.Swimers <>g__initLocal3; 48 49 // Methods 50 [DebuggerHidden] 51 public <GetEnumerator>d__4(int <>1__state) 52 { 53 this.<>1__state = <>1__state; 54 } 55 56 private bool MoveNext() 57 { 58 switch (this.<>1__state) 59 { 60 case 0: 61 this.<>1__state = -1; 62 this.<>g__initLocal0 = new Program.Swimers(); 63 this.<>g__initLocal0.Name = "LBJ"; 64 this.<>2__current = this.<>g__initLocal0; 65 this.<>1__state = 1; 66 return true; 67 68 case 1: 69 this.<>1__state = -1; 70 this.<>g__initLocal1 = new Program.Swimers(); 71 this.<>g__initLocal1.Name = "KB"; 72 this.<>2__current = this.<>g__initLocal1; 73 this.<>1__state = 2; 74 return true; 75 76 case 2: 77 this.<>1__state = -1; 78 this.<>g__initLocal2 = new Program.Swimers(); 79 this.<>g__initLocal2.Name = "KB1"; 80 this.<>2__current = this.<>g__initLocal2; 81 this.<>1__state = 3; 82 return true; 83 84 case 3: 85 this.<>1__state = -1; 86 this.<>g__initLocal3 = new Program.Swimers(); 87 this.<>g__initLocal3.Name = "KB1"; 88 this.<>2__current = this.<>g__initLocal3; 89 this.<>1__state = 4; 90 return true; 91 92 case 4: 93 this.<>1__state = -1; 94 break; 95 } 96 return false; 97 } 98 99 [DebuggerHidden] 100 void IEnumerator.Reset() 101 { 102 throw new NotSupportedException(); 103 } 104 105 void IDisposable.Dispose() 106 { 107 } 108 109 // Properties 110 object IEnumerator<object>.Current 111 { 112 [DebuggerHidden] 113 get 114 { 115 return this.<>2__current; 116 } 117 } 118 119 object IEnumerator.Current 120 { 121 [DebuggerHidden] 122 get 123 { 124 return this.<>2__current; 125 } 126 } 127 } 128 }
C# 迭代器:
1. 实现了IEnumerate 获知 IEnumerate<T> 就能使用。foreach.
2. 编译器自动生成了迭代器的代码。
3. yield return用来向迭代器增加对象。
4. 注意Dispose()
refer this passage:
http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx
浙公网安备 33010602011771号