IEnumerable、IEnumerator、IColle…

初学C#的时候,老是被IEnumerable、IEnumerator、ICollection等这样的接口弄的糊里糊涂,我觉得有必要切底的弄清楚IEnumerable和IEnumerator的本质。

下面我们先看IEnumerable和IEnumerator两个接口的语法定义。其实IEnumerable接口是非常的简单,只包含一个抽象的方法GetEnumerator(),它返回一个可用于循环访问集合的IEnumerator对象。IEnumerator对象有什么呢?它是一个真正的集合访问器,没有它,就不能使用foreach语句遍历集合或数组,因为只有IEnumerator对象才能访问集合中的项,假如连集合中的项都访问不了,那么进行集合的循环遍历是不可能的事情了。那么让我们看看IEnumerator接口有定义了什么东西。看下图我们知道IEnumerator接口定义了一个Current属性,MoveNext和Reset两个方法,这是多么的简约。既然IEnumerator对象时一个访问器,那至少应该有一个Current属性,来获取当前集合中的项吧。

MoveNext方法只是将游标的内部位置向前移动(就是移到一下个元素而已),要想进行循环遍历,不向前移动一下怎么行呢?

详细讲解:

说到IEnumerable总是会和IEnumerator、foreach联系在一起。

C# 支持关键字foreach,允许我们遍历任何数组类型的内容:

//遍历数组的项

int[] myArrayOfInts = {10,20,30,40};

foreach(int i in my myArrayOfInts)

{

    Console.WirteLine(i);

}

虽然看上去只有数组才可以使用这个结构,其实任何支持GetEnumerator()方法的类型都可以通过foreach结构进行运算。

[csharp] view plain copy print ?
  1. public class Garage  
  2.  
  3.     Car[] carArray new Car[4];  //在Garage中定义一个Car类型的数组carArray,其实carArray在这里的本质是一个数组字段  
  4.   
  5.     //启动时填充一些Car对象  
  6.     public Garage()  
  7.      
  8.         //为数组字段赋值  
  9.         carArray[0] new Car("Rusty", 30);  
  10.         carArray[1] new Car("Clunker", 50);  
  11.         carArray[2] new Car("Zippy", 30);  
  12.         carArray[3] new Car("Fred", 45);  
  13.      
  14.  
    public class Garage
    {
        Car[] carArray = new Car[4];  //在Garage中定义一个Car类型的数组carArray,其实carArray在这里的本质是一个数组字段

        //启动时填充一些Car对象
        public Garage()
        {
            //为数组字段赋值
            carArray[0] = new Car("Rusty", 30);
            carArray[1] = new Car("Clunker", 50);
            carArray[2] = new Car("Zippy", 30);
            carArray[3] = new Car("Fred", 45);
        }
    }
 

理想情况下,与数据值数组一样,使用foreach构造迭代Garage对象中的每一个子项比较方便:

[csharp] view plain copy print ?
  1. //这看起来好像是可行的  
  2. lass Program  
  3.     
  4.        static void Main(string[] args)  
  5.         
  6.            Console.WriteLine("*********Fun with IEnumberable/IEnumerator************\n");  
  7.            Garage carLot new Garage();  
  8.   
  9.            //交出集合中的每一Car对象吗  
  10.             foreach (Car in carLot)  
  11.             
  12.                Console.WriteLine("{0} is going {1} MPH", c.CarName, c.CurrentSpeed);  
  13.             
  14.   
  15.            Console.ReadLine();  
  16.         
  17.     
 //这看起来好像是可行的
class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("*********Fun with IEnumberable/IEnumerator************\n");
            Garage carLot = new Garage();

            //交出集合中的每一Car对象吗
             foreach (Car c in carLot)
            {
                Console.WriteLine("{0} is going {1} MPH", c.CarName, c.CurrentSpeed);
            }

            Console.ReadLine();
        }
    }

让人沮丧的是,编译器通知我们Garage类没有实现名为GetEnumerator()的方法(显然用foreach遍历Garage对象是不可能的事情,因为Garage类没有实现GetEnumerator()方法,Garage对象就不可能返回一个IEnumerator对象,没有IEnumerator对象,就不可能调用方法MoveNext(),调用不了MoveNext,就不可能循环的了)。这个方法是有隐藏在System.collections命名空间中的IEnumerable接口定义的。(特别注意,其实我们循环遍历的都是对象而不是类,只是这个对象是一个集合对象

支持这种行为的类或结构实际上是宣告它们向调用者公开所包含的子项:

//这个接口告知调方对象的子项可以枚举

public interface IEnumerable

{

    IEnumerator GetEnumerator();

}

可以看到,GetEnumerator方法返回对另一个接口System.Collections.IEnumerator的引用。这个接口提供了基础设施,调用方可以用来移动IEnumerable兼容容器包含的内部对象。

//这个接口允许调用方获取一个容器的子项

public interface IEnumerator

{

    bool MoveNext();             //将游标的内部位置向前移动

    object Current{get;}       //获取当前的项(只读属性)

    void Reset();                 //将游标重置到第一个成员前面

}

所以,要想Garage类也可以使用foreach遍历其中的项,那我们就要修改Garage类型使之支持这些接口,可以手工实现每一个方法,不过这得花费不少功夫。虽然自己开发GetEnumerator()、MoveNext()、Current和Reset()也没有问题,但有一个更简单的办法。因为System.Array类型和其他许多类型(如List)已经实现了IEnumerable和IEnumerator接口,你可以简单委托请求到System.Array,如下所示:

[csharp] view plain copy print ?
  1. namespace MyCarIEnumerator  
  2.  
  3.     public class Garage:IEnumerable  
  4.      
  5.         Car[] carArray new Car[4];  
  6.   
  7.         //启动时填充一些Car对象  
  8.         public Garage()  
  9.          
  10.             carArray[0] new Car("Rusty", 30);  
  11.             carArray[1] new Car("Clunker", 50);  
  12.             carArray[2] new Car("Zippy", 30);  
  13.             carArray[3] new Car("Fred", 45);  
  14.          
  15.         public IEnumerator GetEnumerator()  
  16.          
  17.             return this.carArray.GetEnumerator();  
  18.          
  19.      
  20.  
  21. //修改Garage类型之后,就可以在C#foreach结构中安全使用该类型了。  
namespace MyCarIEnumerator
{
    public class Garage:IEnumerable
    {
        Car[] carArray = new Car[4];

        //启动时填充一些Car对象
        public Garage()
        {
            carArray[0] = new Car("Rusty", 30);
            carArray[1] = new Car("Clunker", 50);
            carArray[2] = new Car("Zippy", 30);
            carArray[3] = new Car("Fred", 45);
        }
        public IEnumerator GetEnumerator()
        {
            return this.carArray.GetEnumerator();
        }
    }
}
//修改Garage类型之后,就可以在C#foreach结构中安全使用该类型了。
[csharp] view plain copy print ?
  1. //除此之外,GetEnumerator()被定义为公开的,对象用户可以与IEnumerator类型交互:   
  2. namespace MyCarIEnumerator  
  3.  
  4.     class Program  
  5.      
  6.         static void Main(string[] args)  
  7.          
  8.             Console.WriteLine("*********Fun with IEnumberable/IEnumerator************\n");  
  9.             Garage carLot new Garage();  
  10.   
  11.             //交出集合中的每一Car对象吗  
  12.             foreach (Car in carLot)  //之所以遍历carLot,是因为carLot.GetEnumerator()返回的项时Car类型,这个十分重要  
  13.              
  14.                 Console.WriteLine("{0} is going {1} MPH", c.CarName, c.CurrentSpeed);  
  15.              
  16.   
  17.             Console.WriteLine("GetEnumerator被定义为公开的,对象用户可以与IEnumerator类型交互,下面的结果与上面是一致的");  
  18.             //手动与IEnumerator协作  
  19.             IEnumerator carLot.GetEnumerator();  
  20.             while (i.MoveNext())  
  21.               
  22.                 Car myCar (Car)i.Current;  
  23.                 Console.WriteLine("{0} is going {1} MPH", myCar.CarName, myCar.CurrentSpeed);  
  24.              
  25.             Console.ReadLine();  
  26.          
  27.      
  28.  
//除此之外,GetEnumerator()被定义为公开的,对象用户可以与IEnumerator类型交互: 
namespace MyCarIEnumerator
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("*********Fun with IEnumberable/IEnumerator************\n");
            Garage carLot = new Garage();

            //交出集合中的每一Car对象吗
            foreach (Car c in carLot)  //之所以遍历carLot,是因为carLot.GetEnumerator()返回的项时Car类型,这个十分重要
            {
                Console.WriteLine("{0} is going {1} MPH", c.CarName, c.CurrentSpeed);
            }

            Console.WriteLine("GetEnumerator被定义为公开的,对象用户可以与IEnumerator类型交互,下面的结果与上面是一致的");
            //手动与IEnumerator协作
            IEnumerator i = carLot.GetEnumerator();
            while (i.MoveNext())
            { 
                Car myCar = (Car)i.Current;
                Console.WriteLine("{0} is going {1} MPH", myCar.CarName, myCar.CurrentSpeed);
            }
            Console.ReadLine();
        }
    }
}

 

下面我们来看看手工实现IEnumberable接口和IEnumerator接口中的方法:

[csharp] view plain copy print ?
  1. namespace ForeachTestCase  
  2.  
  3.       //继承IEnumerable接口,其实也可以不继承这个接口,只要类里面含有返回IEnumberator引用的GetEnumerator()方法即可  
  4.     class ForeachTest:IEnumerable      
  5.         private string[] elements;  //装载字符串的数组  
  6.         private int ctr 0;  //数组的下标计数器  
  7.   
  8.         ///   
  9.         /// 初始化的字符串  
  10.         ///   
  11.         ///   
  12.         ForeachTest(params string[] initialStrings)  
  13.           
  14.             //为字符串分配内存空间  
  15.             elements new String[8];  
  16.             //复制传递给构造方法的字符串  
  17.             foreach (string in initialStrings)  
  18.              
  19.                 elements[ctr++] s;   
  20.              
  21.          
  22.   
  23.         ///   
  24.         ///  构造函数  
  25.         ///   
  26.         /// 初始化的字符串  
  27.         /// 分隔符,可以是一个或多个字符分隔  
  28.         ForeachTest(string initialStrings, char[] delimiters)   
  29.          
  30.             elements initialStrings.Split(delimiters);  
  31.          
  32.   
  33.         //实现接口中得方法  
  34.         public IEnumerator GetEnumerator()  
  35.          
  36.             return  new ForeachTestEnumerator(this);  
  37.          
  38.   
  39.         private class ForeachTestEnumerator IEnumerator  
  40.          
  41.             private int position -1;  
  42.             private ForeachTest t;  
  43.             public ForeachTestEnumerator(ForeachTest t)  
  44.              
  45.                 this.t t;  
  46.              
  47.  
  48.             #region 实现接口  
  49.   
  50.             public object Current  
  51.              
  52.                 get  
  53.                  
  54.                     return t.elements[position];  
  55.                  
  56.              
  57.   
  58.             public bool MoveNext()  
  59.              
  60.                 if (position t.elements.Length 1)  
  61.                  
  62.                     position++;  
  63.                     return true;  
  64.                  
  65.                 else  
  66.                  
  67.                     return false;  
  68.                  
  69.              
  70.   
  71.             public void Reset()  
  72.              
  73.                 position -1;  
  74.              
  75.  
  76.             #endregion  
  77.          
  78.         static void Main(string[] args)  
  79.          
  80.             // ForeachTest new ForeachTest("This is sample sentence.", new char[] ', '-' });  
  81.             ForeachTest new ForeachTest("This", "is", "a", "sample", "sentence.");  
  82.             foreach (string item in f)  
  83.              
  84.                 System.Console.WriteLine(item);  
  85.              
  86.             Console.ReadKey();  
  87.          
  88.      
  89.  
namespace ForeachTestCase
{
      //继承IEnumerable接口,其实也可以不继承这个接口,只要类里面含有返回IEnumberator引用的GetEnumerator()方法即可
    class ForeachTest:IEnumerable     {
        private string[] elements;  //装载字符串的数组
        private int ctr = 0;  //数组的下标计数器

        /// 
        /// 初始化的字符串
        /// 
        /// 
        ForeachTest(params string[] initialStrings)
        { 
            //为字符串分配内存空间
            elements = new String[8];
            //复制传递给构造方法的字符串
            foreach (string s in initialStrings)
            {
                elements[ctr++] = s; 
            }
        }

        /// 
        ///  构造函数
        /// 
        /// 
初始化的字符串
        /// 
分隔符,可以是一个或多个字符分隔
        ForeachTest(string initialStrings, char[] delimiters) 
        {
            elements = initialStrings.Split(delimiters);
        }

        //实现接口中得方法
        public IEnumerator GetEnumerator()
        {
            return  new ForeachTestEnumerator(this);
        }

        private class ForeachTestEnumerator : IEnumerator
        {
            private int position = -1;
            private ForeachTest t;
            public ForeachTestEnumerator(ForeachTest t)
            {
                this.t = t;
            }

            #region 实现接口

            public object Current
            {
                get
                {
                    return t.elements[position];
                }
            }

            public bool MoveNext()
            {
                if (position < t.elements.Length - 1)
                {
                    position++;
                    return true;
                }
                else
                {
                    return false;
                }
            }

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

            #endregion
        }
        static void Main(string[] args)
        {
            // ForeachTest f = new ForeachTest("This is a sample sentence.", new char[] { ' ', '-' });
            ForeachTest f = new ForeachTest("This", "is", "a", "sample", "sentence.");
            foreach (string item in f)
            {
                System.Console.WriteLine(item);
            }
            Console.ReadKey();
        }
    }
}

 

IEnumerable接口

实现了IEnmerable接口的集合,是强类型的。它为子对象的迭代提供类型更加安全的方式。

[csharp] view plain copy print ?
  1. public  class ListBoxTest:IEnumerable  
  2.     
  3.        private string[] strings;  
  4.        private int ctr 0;  
  5.       
  6.        #region IEnumerable 成员  
  7.        //可枚举的类可以返回枚举  
  8.        public IEnumerator<<span class="keyword">string> GetEnumerator()  
  9.         
  10.            foreach (string in strings)  
  11.             
  12.                yield return s;  
  13.             
  14.         
  15.  
  16.        #endregion  
  17.  
  18.        #region IEnumerable 成员  
  19.        //显式实现接口  
  20.        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()  
  21.         
  22.            return GetEnumerator();  
  23.         
  24.  
  25.        #endregion  
  26.   
  27.        //用字符串初始化列表框  
  28.        public ListBoxTest(params string[] initialStrings)  
  29.          
  30.            //为字符串分配内存空间  
  31.            strings new String[8];  
  32.            //复制传递给构造方法的字符串  
  33.            foreach (string in initialStrings)  
  34.             
  35.                strings[ctr++] s;   
  36.             
  37.         
  38.   
  39.        //在列表框最后添加一个字符串  
  40.        public void Add(string theString)  
  41.          
  42.            strings[ctr] theString;  
  43.            ctr++;  
  44.         
  45.   
  46.        //允许数组式的访问  
  47.        public string this[int index]  
  48.         
  49.            get  
  50.                if (index || index >= strings.Length)  
  51.                  
  52.                    //处理不良索引  
  53.                 
  54.                return strings[index];  
  55.             
  56.            set   
  57.                strings[index] value;  
  58.             
  59.         
  60.   
  61.        //发布拥有的字符串数  
  62.        public int GetNumEntries()  
  63.         
  64.            return ctr;  
  65.         
  66.     
 public  class ListBoxTest:IEnumerable
    {
        private string[] strings;
        private int ctr = 0;
      
        #region IEnumerable 成员
        //可枚举的类可以返回枚举
        public IEnumerator GetEnumerator()
        {
            foreach (string s in strings)
            {
                yield return s;
            }
        }

        #endregion

        #region IEnumerable 成员
        //显式实现接口
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion

        //用字符串初始化列表框
        public ListBoxTest(params string[] initialStrings)
        { 
            //为字符串分配内存空间
            strings = new String[8];
            //复制传递给构造方法的字符串
            foreach (string s in initialStrings)
            {
                strings[ctr++] = s; 
            }
        }

        //在列表框最后添加一个字符串
        public void Add(string theString)
        { 
            strings[ctr] = theString;
            ctr++;
        }

        //允许数组式的访问
        public string this[int index]
        {
            get {
                if (index < 0 || index >= strings.Length)
                { 
                    //处理不良索引
                }
                return strings[index];
            }
            set { 
                strings[index] = value;
            }
        }

        //发布拥有的字符串数
        public int GetNumEntries()
        {
            return ctr;
        }
    }
[csharp] view plain copy print ?
  1. class Program  
  2.    
  3.       static void Main(string[] args)  
  4.        
  5.           //创建一个新的列表框并初始化  
  6.           ListBoxTest lbt new ListBoxTest("Hello", "World");  
  7.   
  8.           //添加新的字符串  
  9.           lbt.Add("Who");  
  10.           lbt.Add("Is");  
  11.           lbt.Add("Douglas");  
  12.           lbt.Add("Adams");  
  13.   
  14.           //测试访问  
  15.           string subst "Universe";  
  16.           lbt[1] subst;  
  17.   
  18.           //访问所有的字符串  
  19.           foreach (string in lbt)  
  20.            
  21.               Console.WriteLine("Value:{0}", s);  
  22.            
  23.           Console.ReadKey();  
  24.        
  25.    
  class Program
    {
        static void Main(string[] args)
        {
            //创建一个新的列表框并初始化
            ListBoxTest lbt = new ListBoxTest("Hello", "World");

            //添加新的字符串
            lbt.Add("Who");
            lbt.Add("Is");
            lbt.Add("Douglas");
            lbt.Add("Adams");

            //测试访问
            string subst = "Universe";
            lbt[1] = subst;

            //访问所有的字符串
            foreach (string s in lbt)
            {
                Console.WriteLine("Value:{0}", s);
            }
            Console.ReadKey();
        }
    }


 综上所述,一个类型是否支持foreach遍历,必须满足下面条件:

方案1:让这个类实现IEnumerable接口

方案2:这个类有一个public的GetEnumerator的实例方法,并且返回类型中有public 的bool MoveNext()实例方法和public的Current实例属性。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值