球球圆圆豆豆 / 容器介绍 / C#中要使一个类支持FOREACH遍历,实现过程...

分享

   

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

2015-11-30  球球圆圆...

一个类型要想支持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("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);

            }

        }

   }      

}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多
    喜欢该文的人也喜欢 更多

    ×
    ×

    ¥.00

    微信或支付宝扫码支付:

    开通即同意《个图VIP服务协议》

    全部>>