久久国产成人av_抖音国产毛片_a片网站免费观看_A片无码播放手机在线观看,色五月在线观看,亚洲精品m在线观看,女人自慰的免费网址,悠悠在线观看精品视频,一级日本片免费的,亚洲精品久,国产精品成人久久久久久久

分享

C#中要使一個類支持FOREACH遍歷,實現(xiàn)過程怎樣?

 球球圓圓豆豆 2015-11-30

一個類型要想支持foreach則必須實現(xiàn)IEnumerable,,IEnumerator兩個接口。 
// Namespace: System.Collections, Library: BCL
public interface IEnumerable...{
    IEnumerator GetEnumerator();
}
 // Namespace: System.Collections, Library: BCL
public interface IEnumerator...{
    bool MoveNext();
    void Reset();
    object Current ...{ get; }
}

 

實例:

using System;

using System.Collections.Generic;

using System.Windows.Forms;

using System.Collections;

namespace Randam

{

    public class car

    {

        string name;

        int year;

        public car(string str, int num)

        {

            name = str;

            year = num;

        }

        public string Name

        {

            get

            {

                return name;

            }

        }

    }

    public class cars : IEnumerator,IEnumerable

   {

      private car[] carlist;

      int position = -1;

      //Create internal array in constructor.

      public cars()

      {

          carlist= new car[6]

          {

             new car("Ford",1992),

             new car("Fiat",1988),

             new car("Buick",1932),

             new car("Ford",1932),

             new car("Dodge",1999),

             new car("Honda",1977)

          };

      }

      //IEnumerator and IEnumerable require these methods.

      public IEnumerator GetEnumerator()

      {

         return (IEnumerator)this;

          }

      //IEnumerator

      public bool MoveNext()

      {

         position++;

         return (position < carlist.Length);

      }

      //IEnumerable

      public void Reset()

      {position = 0;}

      //IEnumerable

      public object Current

      {

         get

         {

            try 

            {

              return carlist[position];

            }

            catch (IndexOutOfRangeException)

            {

              throw new InvalidOperationException();

            }

         }

      }

        public static void Main()

        {

            cars cars = new cars();

            foreach (car s in cars)

            {

                Console.WriteLine("cars value: {0}", s.Name);

            }

            IEnumerator ienum = (IEnumerator)cars.GetEnumerator();

            ienum.Reset();

            Console.WriteLine("***************************");

            while (ienum.MoveNext())

            {

                car s = (car)ienum.Current;

                Console.WriteLine("cars value: {0}", s.Name);

            }

        }

   }      

}

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,,所有內(nèi)容均由用戶發(fā)布,,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式,、誘導(dǎo)購買等信息,,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,,請點擊一鍵舉報,。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多