C#复习笔记(7) --接口

Posted on 2006-09-15 23:31  raekwon  阅读(102)  评论(0)    收藏  举报
接口
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] {124433250};
   }

   
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);
      }
   }
}

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3