Chinaunix首页 | 论坛 | 博客
  • 博客访问: 170305
  • 博文数量: 48
  • 博客积分: 1410
  • 博客等级: 上尉
  • 技术积分: 640
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-22 15:54
文章分类
文章存档

2011年(2)

2010年(13)

2009年(30)

2008年(3)

我的朋友

分类:

2009-01-09 11:06:43

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

            }

        }

   }      

}

阅读(5557) | 评论(0) | 转发(0) |
0

上一篇:锁定缓冲

下一篇:吞吐量

给主人留下些什么吧!~~