溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

IEnumerable接口與IEnumerator接口

發(fā)布時(shí)間:2020-04-30 05:45:56 來(lái)源:網(wǎng)絡(luò) 閱讀:464 作者:1473348968 欄目:編程語(yǔ)言

通過(guò)一個(gè)例子來(lái)看

-------------------------------------------------------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
    {
        //數(shù)組
        public string[] s;
        //索引器
        public int i;
        public Student(string[] str)//構(gòu)造函數(shù),初始化數(shù)組
        {
            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對(duì)象
        Student s;
        //游標(biāo)
        int i = -1;
        public StiAll(Student ss)//構(gòu)造函數(shù),初始化student對(duì)象
        {
            this.s = ss;
        }
 
        public object Current//獲取當(dāng)前的項(xiàng)(只讀屬性)
        {
            get { return s.s[i]; }
        }
        public bool MoveNext()//將游標(biāo)的位置向前移動(dòng)
        {
            if (i<s.s.Length-1)//如果在s數(shù)組的長(zhǎng)度范圍之內(nèi)就返回true
            {
                i++;
                return true;
            }
            else
            {
                return false;
            }
        }
        public void Reset()//初始化游標(biāo)
        {
            i = -1;
        }
    }
}

-------------------------------------------------------主程序

 Student s = new Student(new string[] { "呂蒙", "周泰", "黃蓋" });//實(shí)例化Student對(duì)象
            //第一種方式遍歷
            foreach (var item in s)
            {
                Console.WriteLine(item);//輸出呂蒙,周泰,黃蓋
            }
            //第二種方式遍歷
            StiAll sa = new StiAll(s);
            while (sa.MoveNext())
            {
                Console.WriteLine(sa.Current);//輸出呂蒙,周泰,黃蓋
            }
            Console.ReadKey();

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI