C#中要使一个类支持FOREACH遍历,实现过程怎样? [转]

http://blog.chinaunix.net/uid-20796829-id-466658.html

一个类型要想支持foreach则必须实现IEnumerableIEnumerator两个接口。  
// 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("car’s value: {0}", s.Name);

            }

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

            ienum.Reset();

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

            while (ienum.MoveNext())

            {

                car s = (car)ienum.Current;

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

            }

        }

   }      

}

转载于:https://www.cnblogs.com/Uinkanade/articles/3976864.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值