C#复习笔记(7)

接口
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);
      }
   }
}
<script type="text/javascript"> // </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值