IEnumerable和IEnumerator

IEnumerable接口和IEnumerator是两个比较重要的接口,当实现了该接口,就可以在Foreach中使用。下面来看看这两个东西。

IEnumerable是一个声明式的接口,声明实现该接口的Class是Enumerable的,但并没有说明如何实现枚举器,IEnumerable的接口成员只有一个,那就是GetEnumerator方法,它返回对象的枚举数。

public interface IEnumerable {
        IEnumerator GetEnumerator();
    }

IEnumerator是一个实现式的接口,IEnumerator的接口包括三个成员函数:Current,MoveNext和Reset。

public interface IEnumerator {
        object Current { get; }   //返回当前位置项的属性,因为是Object的类型引用,所以可以返回任何类型。
        bool MoveNext();      //把枚举的位置前进到下一项的,如果新位置有效则返回True,如果无效(比如到达了尾部),则返回False。
        void Reset();        //把位置重置到原始状态。
    }

如果某类想实现Foreach,分别实现这两个接口,IEnumerable和IEnumerator通过IEnumerable的GetEnumerator()方法建立了连接。

下面这个例子就实现了这两个接口,然后根据内容来Foreach,把内容显示出来~

View Code
class Program {
        static void Main(string[] args) {
            MyTestClass mt = new MyTestClass();
            foreach (var each in mt) {
                Console.WriteLine(each);
            }
        }
    }

    class TestName : IEnumerator {
        String[] Name;
        int pos = -1;
        public TestName(string[] name) {
            Name = new string[name.Length];
            for (int i = 0; i < name.Length; i++) {
                this.Name[i] = name[i];
            }
        }

        public object Current {        //Current
            get { return Name[pos]; }
        }

        public bool MoveNext() {    //MoveNext
            if (pos < Name.Length - 1) {
                pos++;
                return true;
            } else { return false; }
        }

        public void Reset() {    //Reset
            pos = -1;
        }
    }

    class MyTestClass : IEnumerable {
        string[] Name = { "AA", "BB", "CC", "DD" };
        public IEnumerator GetEnumerator() {
            return new TestName(Name);        //枚举数类的实例
        }
    }

 

posted @ 2013-02-25 14:55  世界很灰暗  阅读(300)  评论(0编辑  收藏  举报