C#--IEnumerable 与 IEnumerator 的区别

一、 IEnumerator 

         解释:它是一个的集合访问器,使用foreach语句遍历集合或数组时,就是调用 Current、MoveNext()的结果。

// 定义如下
public interface IEnumerator { // 返回结果: 集合中的当前元素。 object Current { get; } // 返回结果: 如果枚举数成功地推进到下一个元素,则为 true;如果枚举数越过集合的结尾,则为 false。 bool MoveNext(); // 调用结果:将枚举数设置为其初始位置,该位置位于集合中第一个元素之前。 void Reset(); }

 

二、IEnumerable

        解释:它利用 GetEnumerator() 返回 IEnumerator 集合访问器。

 // 定义如下
        public interface IEnumerable
        {
            // 返回结果: 可用于循环访问集合的IEnumerator 对象。
            IEnumerator GetEnumerator();
        }

 

三、举个栗子   

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

namespace ArrayListToList
{
    // 定义student类
    public class Student
    {
        public string Id { get; set; }

        public string Name { get; set; }

        public string Remarks { get; set; }

        public Student(string id, string name, string remarks)
        {
            this.Id = id;
            this.Name = name;
            this.Remarks = remarks;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            ArrayList arrStus = new ArrayList
            {
                new Student("1313001", "liuliu"," little rabbit"),
                new Student("1313002", "zhangsan", "little tortoise")
            };
            // List<T> 继承了IEnumerable<T>,  IEnumerble<T>继承了IEnumerable.
            List<Student> stuL = ArrListToArr<Student>(arrStus);
            foreach(Student stu in stuL)
            {
                Console.WriteLine($"{ stu.Name + "  " + stu.Id + "  " + stu.Remarks }");
            };
        }

        // arrList 转换为 List<T>
        // ArrList 定义时已继承了IEnumerable
        static List<T> ArrListToArr<T>(ArrayList arrL)
        {
            List<T> list = new List<T>();
            
            IEnumerator enumerator = arrL.GetEnumerator();
            
            while (enumerator.MoveNext())
            {
                 T item = (T)(enumerator.Current);
                 list.Add(item);
            }
           
            return list;
        }
    }
}

   

 结果:

 

posted @ 2017-09-06 13:46  Mileres  阅读(5966)  评论(1编辑  收藏  举报