IEnumerable 和 IEnumerator

IEnumerable 接口只包含一个抽象的方法 GetEnumerator(),它返回一个可用于循环访问集合的 IEnumerator 对象,IEnumerator 对象是一个集合访问器。

需要给自定义的类实现 foreach 功能,就需要实现 IEnumerable 接口,下面给出一个例子。

using System;
using System.Collections;
using System.Collections.Generic;

class NewList<T> : IEnumerable          //实现 IEnumerable 接口的 GetEnumerator() 
{
    private List<T> newList = new List<T>();

    public void Add(T item)
    {
        newList.Add(item);
    }
    public IEnumerator GetEnumerator()
    {
        return this.newList.GetEnumerator();
    }
}

class Program
{
    static void Main(string[] args)
    {
        NewList<string> newList = new NewList<string>();
        newList.Add("a");
        newList.Add("b");
        foreach(string item in newList)
        {
            Console.WriteLine("item:" + item);
        }
    }
}

 

手工实现IEnumberable接口和IEnumerator接口中的方法实现的方式如下:

using System;
using System.Collections;
using System.Collections.Generic;

class NewList<T> : IEnumerable          //实现 IEnumerable 接口的 GetEnumerator() 
{
    private List<T> list = new List<T>();
    
    public void Add(T item)
    {
        list.Add(item);
    }
    public IEnumerator GetEnumerator()
    {
        return new NewListEnumerator<T>(this);
    }

    private class NewListEnumerator<T>: IEnumerator
    {
        private int position = -1;
        private NewList<T> newList;
        public NewListEnumerator(NewList<T> newList)
        {
            this.newList = newList;
        }

        public object Current
        {
            get 
            {
                return newList.list[position];
            }
        }

        public bool MoveNext()
        {
            if(position < newList.list.Count - 1)
            {
                position++;
                return true;
            }
            else
            {
                return false;
            }
        }

        public void Reset()
        {
            position = -1;
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        NewList<string> newList = new NewList<string>();
        newList.Add("a");
        newList.Add("b");
        foreach(string item in newList)
        {
            Console.WriteLine("item:" + item);
        }
    }
}

 

posted @ 2015-10-29 17:22  轻典  阅读(295)  评论(0编辑  收藏  举报