IEnumerable介面與IEnumerator介面

來源:互聯網
上載者:User

標籤:c# ienumerable與ienumerator   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();        }    }}

-------------------------------------------------------StiAll.cs

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();

本文出自 “程式猿的家” 部落格,請務必保留此出處http://962410314.blog.51cto.com/7563109/1529891

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.