标签:
public class HelloCollection { public IEnumerator<string> GetEnumerator() { yield return "Hello"; yield return "World"; } }
static void Main(string[] args) { HelloCollection collection = new HelloCollection(); foreach (string s in collection) Console.WriteLine(s); }
1 public class HelloCollection 2 { 3 public IEnumerator GetEnumerator() 4 { 5 return new Enumerator(0); 6 } 7 public class Enumerator : IEnumerator<string>, IEnumerator, IDisposable 8 { 9 private int state; 10 private string current; 11 12 public Enumerator(int state) { this.state = state; } 13 bool System.Collections.IEnumerator.MoveNext() 14 { 15 switch (state) 16 { 17 case 0: 18 current = "Hello"; 19 state = 1; 20 return true; 21 case 1: 22 current = "World"; 23 state = 2; 24 return true; 25 case 2: 26 break; 27 } 28 return false; 29 } 30 void System.Collections.IEnumerator.Reset() 31 { 32 throw new NotSupportedException(); 33 } 34 string System.Collections.Generic.IEnumerator<string>.Current 35 { 36 get { return current; } 37 } 38 object System.Collections.IEnumerator.Current 39 { 40 get { return current; } 41 } 42 void IDisposable.Dispose() { } 43 } 44 }
1 public class MusicTitles 2 { 3 string[] names = { "Tubular Bells", "Hergest Ridge", "Ommadawn", "Platinum" }; 4 5 public IEnumerator<string> GetEnumerator() 6 { 7 for (int i = 0; i < 4; i++) 8 yield return names[i]; 9 } 10 public IEnumerable<string> Reverse() 11 { 12 for (int i = 3; i >= 0; i--) 13 yield return names[i]; 14 } 15 public IEnumerable<string> Subset(int index, int length) 16 { 17 for (int i = index; i < index + length; i++) 18 yield return names[i]; 19 } 20 }
1 public class GameMoves 2 { 3 private IEnumerator cross; 4 private IEnumerator circle; 5 6 public GameMoves() 7 { 8 cross = Cross(); 9 circle = Circle(); 10 } 11 private int move = 0; 12 const int MaxMoves = 9; 13 14 public IEnumerator Cross() 15 { 16 while (true) 17 { 18 Console.WriteLine("Cross, move {0}", move); 19 if (++move >= MaxMoves) 20 yield break; 21 yield return circle; 22 } 23 } 24 public IEnumerator Circle() 25 { 26 while (true) 27 { 28 Console.WriteLine("Circle, move {0}", move); 29 if (++move >= MaxMoves) yield break; 30 yield return cross; 31 } 32 } 33 }
var game = new GameMoves(); IEnumerator enumerator = game.Cross(); while (enumerator.MoveNext()) enumerator = enumerator.Current as IEnumerator;
标签:
原文地址:http://www.cnblogs.com/ChrisLi/p/4191054.html