您的位置:首页 > 编程语言 > C#

C#复习笔记(7)

2006-12-18 00:07 381 查看
接口
using System;
using System.Collections;

// Declare the collection and implement the IEnumerable interface:
public class MyCollection: IEnumerable 
{
   int[] items;
   public MyCollection() 
   {
      items = new int[5] {12, 44, 33, 2, 50};
   }

   public MyEnumerator GetEnumerator() 
   {
      return new MyEnumerator(this);
   }

   // Implement the GetEnumerator() method:
   IEnumerator IEnumerable.GetEnumerator() 
   {
      return GetEnumerator();
   }
    //以上两个接口实现方法可以用下面的一个方法代替
//
//    public IEnumerator GetEnumerator() 
//    {
//        return new MyEnumerator(this);
//    }

   // Declare the enumerator and implement the IEnumerator 
   // and IDisposable interfaces
   public class MyEnumerator: IEnumerator, IDisposable
   {
      int nIndex;
      MyCollection collection;
      public MyEnumerator(MyCollection coll) 
      {
         collection = coll;
         nIndex = -1;
      }

      public void Reset() 
      {
         nIndex = -1;
      }

      public bool MoveNext()
      {
         nIndex++;
         return (nIndex < collection.items.GetLength(0));
      }

      public int Current 
      {
         get 
         {
            return (collection.items[nIndex]);
         }
      }

      // The current property on the IEnumerator interface:
      object IEnumerator.Current 
      {
         get 
         {
            return (Current);
         }
      }
   
      public void Dispose()
      {
         Console.WriteLine("In Dispose");
         collection = null;
      }
   }
}

public class MainClass 
{
   public static void Main(string [] args) 
   {
      MyCollection col = new MyCollection();
      Console.WriteLine("Values in the collection are:");

      // Display collection items:
      foreach (int i in col) 
      {
         Console.WriteLine(i);
      }
   }
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息