IEnumerable 和 IEnumerator 接口

IEnumerator:提供在普通集合中遍历的接口,有Current,MoveNext(),Reset(),其中Current返回的是object类型。
IEnumerable: 暴露一个IEnumerator,支持在普通集合中的遍历。
IEnumerator<T>:继承自IEnumerator,有Current属性,返回的是T类型。
IEnumerable<T>:继承自IEnumerable,暴露一个IEnumerator<T>,支持在泛型集合中遍历。

1. 要使自定义的集合类型支持foreach访问,就要实现IEnumerable接口。
2. 在很多地方有讨论为什么新增加的泛型接口IEnumerable<T>要继承IEnumerable,这是为了兼容。理论上所有的泛型接口都要继承自所有的非泛型接口。例如在.net 1.1中有个方法接收的是IEnumerable类型的参数,当移植到新的环境下,我们传入一个IEnumerable<T>的参数,它也是可以被接受的,因为他们完成的都是枚举的行为。

然而特殊的是IList<T>没有继承自IList接口,因为如果让IList<T>继承IList的话,那么是实现IList<int>的类就需要实现两个Insert方法,一个是IList<int>的void Insert(int index, int item),另外一个是IList的void Insert(int index, object item),这是就有一个接口可以把object类型的数据插入到IList<int>集合中了,这是不对的,所以不继承。

而IEnumerable<T>不同的是,它只有”输出“的作用,也就是说我们只会从它里面取数据,所以不会有上面描述的混乱出现。

3. 下面的例子描述了如何使用
首先,有一个Person类:

public class Person
    {
        public string firstName { get; set; }
        public string lastName { get; set; }
    }

第一种方式实现People集合:

    public class People : IEnumerable
    {
        private Person[] _people;
        public People(Person[] pArray)
        {
            _people = new Person[pArray.Length];

            for (int i = 0; i < pArray.Length; i++)
            {
                _people[i] = pArray[i];
            }
        }
        
        //IEnumerable Members
        IEnumerator IEnumerable.GetEnumerator()
        {
            return new PeopleEnum(_people);
        }
    }

    public class PeopleEnum : IEnumerator
    {
        public Person[] _people;

        // Enumerators are positioned before the first element
        // until the first MoveNext() call.
        int position = -1;

        public PeopleEnum(Person[] list)
        {
            _people = list;
        }
        
        public bool MoveNext()
        {
            position++;
            return (position < _people.Length);
        }

        public void Reset()
        {
            position = -1;
        }
        
        //IEnumerator Members
        object IEnumerator.Current
        {
            get
            {
                try
                {
                    return _people[position];
                }
                catch (IndexOutOfRangeException)
                {
                    throw new IndexOutOfRangeException();
                }
            }
        }
    }
第二种方式,让People自己也实现IEnumerator接口:
    public class People : IEnumerable, IEnumerator
    {
        private Person[] _people;
        int position = -1;

        public People(Person[] pArray)
        {
            _people = new Person[pArray.Length];

            for (int i = 0; i < pArray.Length; i++)
            {
                _people[i] = pArray[i];
            }
        }
        
        public IEnumerator GetEnumerator()
        {
            return this;
        }

        public bool MoveNext()
        {
            position++;
            return (position < _people.Length);
        }

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

        public object Current
        {
            get
            {
                try
                {
                    return _people[position];
                }
                catch (IndexOutOfRangeException)
                {
                    throw new IndexOutOfRangeException();
                }
            }
        }
    }
第三种方式,用泛型指定了类型:
    public class People : IEnumerable<Person>
    {
        private Person[] _people;
        public People(Person[] pArray)
        {
            _people = new Person[pArray.Length];

            for (int i = 0; i < pArray.Length; i++)
            {
                _people[i] = pArray[i];
            }
        }

        //IEnumerable<Person> Members
        public IEnumerator<Person> GetEnumerator()
        {
            return new PeopleEnum(_people);
        }

        //IEnumerable Members
        IEnumerator IEnumerable.GetEnumerator()
        {
            return new PeopleEnum(_people);
        }
    }

    public class PeopleEnum : IEnumerator<Person>
    {
        public Person[] _people;

        // Enumerators are positioned before the first element
        // until the first MoveNext() call.
        int position = -1;

        public PeopleEnum(Person[] list)
        {
            _people = list;
        }

        // IEnumerator<T>继承了IDisposable,为了遍历完后清理状态,所以需要实现该方法  
        // 该方法在foreach循环完毕后自动调用  
        public void Dispose() { }

        public bool MoveNext()
        {
            position++;
            return (position < _people.Length);
        }

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

        //IEnumerator<Person> Members
        public Person Current
        {
            get
            {
                try
                {
                    return _people[position];
                }
                catch (IndexOutOfRangeException)
                {
                    throw new InvalidOperationException();
                }
            }
        }

        //IEnumerator Members
        object IEnumerator.Current
        {
            get
            {
                try
                {
                    return _people[position];
                }
                catch (IndexOutOfRangeException)
                {
                    throw new IndexOutOfRangeException();
                }
            }
        }
    }
然后就可以用foreach对自定义集合访问了:
        static void Main()
        {
            Person[] peopleArray = new Person[3]
            {
                new Person() { firstName="John", lastName="Smith"},
                new Person(){firstName="Jim", lastName="Johnson"},
                new Person(){firstName="Sue", lastName="Rabon"}
            };

            People peopleList = new People(peopleArray);
            foreach (Person p in peopleList)
            {
                Console.WriteLine(p.firstName + " " + p.lastName);
            }
            Console.ReadKey();
        }

下面介绍yield关键字的用法:

注意两点:第一,它只能用在一个iterator的方法中,也就是说这个方法的返回值类型只能是IEnumerableIEnumeratorIEnumerable<T>IEnumerator<T>;第二,它只有两种语法:yield return 表达式;或者是yield break
例如下面用yield return返回循环中每一个满足条件的值,但是并不退出方法:

    public static class NumberList
    {
        // Create an array of integers. 
        public static int[] ints = { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377 };
        // Define a property that returns only the even numbers.
        public static IEnumerable<int> GetEven()
        {
            // Use yield to return the even numbers in the list.
            foreach (int i in ints)
            {
                if (i % 2 == 0)
                {
                    yield return i;
                }
            }
        }
    }
调用的地方如下:
        static void Main()
        {
            // Display the even numbers.
            Console.WriteLine("Even numbers");
            foreach (int i in NumberList.GetEven())
            {
                Console.WriteLine(i);
            }
            Console.ReadKey();
        }
在这种用iterator的循环中,只能用yield break退出循环(也退出了整个方法),若是用break是编译不过的。例如:

<pre name="code" class="csharp"><span style="font-family:Microsoft YaHei;font-size:14px;">    public static class NumberList
    {
        // Create an array of integers. 
        public static int[] ints = { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377 };

        // Define a property that returns only the even numbers.
        public static IEnumerable<int> GetEven()
        {
            // Use yield to return the even numbers in the list.
            foreach (int i in ints)
            {
                if (i % 2 == 0)
                {
                    yield break;
                }
            }
            Console.WriteLine();
        }
    }</span>
 
如果yield break;会被执行到的话,则后面的Console.WriteLine();是不会被执行的,整个方法体已经在yield break被执行后就退出了。

另外下面这种写法:

<pre name="code" class="csharp">    public static IEnumerable<int> GetValues()
    {
        yield return 1;
        yield return 2;
        yield return 3;
        yield return 4;
    }
 
则可以用 

    static void Main()
    {
        // Display the even numbers.
        Console.WriteLine("Even numbers");

        foreach (int i in NumberList.GetValues())
        {
            Console.WriteLine(i);
        }
        Console.ReadKey();
    }
来输出,第一次取第一个yield return的值1,第二次取第二个yield return的值2,依此类推。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值