天天看點

IEnumerable接口與IEnumerator接口

通過一個例子來看

-------------------------------------------------------Student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace ConsoleApplication6
{
    public class Student:IEnumerable
    {
        //數組
        public string[] s;
        //索引器
        public int i;
        public Student(string[] str)//構造函數,初始化數組
        {
            s = str;
        }
        public IEnumerator GetEnumerator()//疊代器
        {
            return s.GetEnumerator();
        }
    }
}      
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace ConsoleApplication6
{
    public class StiAll:IEnumerator
    {
        //student對象
        Student s;
        //遊标
        int i = -1;
        public StiAll(Student ss)//構造函數,初始化student對象
        {
            this.s = ss;
        }
 
        public object Current//擷取目前的項(隻讀屬性)
        {
            get { return s.s[i]; }
        }
        public bool MoveNext()//将遊标的位置向前移動
        {
            if (i<s.s.Length-1)//如果在s數組的長度範圍之内就傳回true
            {
                i++;
                return true;
            }
            else
            {
                return false;
            }
        }
        public void Reset()//初始化遊标
        {
            i = -1;
        }
    }
}      
 Student s = new Student(new string[] { "呂蒙", "周泰", "黃蓋" });//執行個體化Student對象
            //第一種方式周遊
            foreach (var item in s)
            {
                Console.WriteLine(item);//輸出呂蒙,周泰,黃蓋
            }
            //第二種方式周遊
            StiAll sa = new StiAll(s);
            while (sa.MoveNext())
            {
                Console.WriteLine(sa.Current);//輸出呂蒙,周泰,黃蓋
            }
            Console.ReadKey();