实现自定义集合
我们可以通过实现 IEnumberable 接口和 IEnumerator 接口实现自定义集合。
1 public class MySet : IEnumerable 2 { 3 internal object[] values; 4 public MySet(object[] values) 5 { 6 this.values = values; 7 } 8 public IEnumerator GetEnumerator() 9 { 10 return new MySetIterator(this); 11 } 12 } 13 //实现自定义迭代器: 14 public class MySetIterator : IEnumerator 15 { 16 MySet set; 17 int position; 18 internal MySetIterator(MySet set) 19 { 20 this.set = set; 21 position = -1; 22 } 23 public object Current 24 { 25 get 26 { 27 if (position == -1 || position == set.values.Length) 28 { 29 throw new InvalidOperationException(); 30 } 31 int index = position; 32 return set.values[index]; 33 } 34 } 35 public bool MoveNext() 36 { 37 if (position != set.values.Length) 38 { 39 position++; 40 } 41 return position < set.values.Length; 42 } 43 public void Reset() 44 { 45 position = -1; 46 } 47 }