打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

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

            }

        }

   }      

}

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C#中的迭代器(详解yield)
IEnumerator、IEnumerable傻傻分不清楚?
面向对象设计(二)——对象间的关系引发的思考
IEnumerable和IEnumerator介绍和区别
LINQ探秘:实现一个自己的LINQ Provider - .NET技术 / C#
.Net中的设计模式——Iterator模式
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服