用foreach可以遍历集合中所有元素,实现:c#编译器会把foreach语句转换为IEnumerable接口中的方法和属性,例如
- foreach(var val in intseq)
- {
- Console.WriteLine(val);
- }
c#编译器把上述代码转换为:
- IEnumerator enumerator =intseq.GetEnumerator;
- while(enumerator.MoveNext())
- {
- int p=(int)enumerator.Current;
- Console.WriteLine(p);
- }
如果编写自定义的类可以用foreach遍历,那么必须实现两个接口IEnumerable和IEnumerator
- public interface IEnumerable
- {
- IEnumerator GetEnumerator();
- }
- public interface IEnumerator
- {
- bool MoveNext();
- void Reset();
- Object Current { get; }
- }
例子:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Collections;
-
- namespace @foreach
- {
- class IntSequence:IEnumerable,IEnumerator
- {
- private int index;
- private int[] arr;
- public IntSequence(int n)
- {
- index = -1;
- arr=new int[n];
- for (int i = 0; i < arr.Length; ++i)
- {
- arr[i] = i + 1;
- }
- }
- public IEnumerator GetEnumerator()
- {
- return (IEnumerator)this;
- }
- public void Reset()
- {
- index = -1;
- }
- public object Current
- {
- get
- {
- return arr[index];
- }
- }
- public bool MoveNext()
- {
- index++;
- return index < arr.Length;
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- IntSequence intseq = new IntSequence(10);
- foreach (var val in intseq)
- {
- Console.WriteLine(val);
- }
- }
- }
- }