对象枚举遍历实现二

ExpandedBlockStart.gif 代码
      // 可枚举对象并非必须实现IEnumerable接口。该职责可以委托给第三个类来实现。
      public   class  Persons
    {  
         
string [] m_Names;
         
public  Persons( params   string [] Names)
         {
                m_Names 
=   new   string [Names.Length];
                Names.CopyTo(m_Names, 
0 );
         }
         
private   string   this [ int  index]
         {
             
get  {  return  m_Names[index]; }
             
set  { m_Names[index]  =  value; }

         }
           
         
private   class  PersonsEnumerator : IEnumerator
         {

           
            
int  index  =   - 1 ;
            
            Persons p;
            
public  PersonsEnumerator(Persons p)
            {
                
this .p  =  p;
            }
            
public   bool  MoveNext()
            {
                index
++ ;
                
return  index  <  p.m_Names.Length;
            }
            
public   void  Reset()
            {
                index 
=   - 1 ;
            }
            
public   object  Current
            {
                
get
                {
                    
return  p.m_Names[index];
                }
            }
         }
         
private   class  PersonsEnumerable : IEnumerable
         {
             
private  Persons m_persons;
             
internal  PersonsEnumerable(Persons persons)
             {
                 m_persons 
=  persons;
             }
             IEnumerator IEnumerable.GetEnumerator()
             {
                 
return   new  PersonsEnumerator(m_persons);
             }


         }
         
public  IEnumerable InOrder
         {
             
get  {    return   new  PersonsEnumerable( this ); }
         }
         
public  IEnumerable Reverse
         {
             
get  
             {
                 
int  length = this .m_Names.Length;
                 Persons persons
=   new  Persons();
                 persons.m_Names 
=   new   string [length];
                 
for  ( int  i  =   0 ; i  <  length; i ++ )
                 {
                    
                     persons.m_Names[i] 
=  m_Names[length - i - 1 ]; 
                 }
                 
return   new  PersonsEnumerable(persons);

             }
         }
        
    }
       实现代码:
       
public    static   void  EnumObject()
        {
            Persons p 
=   new  Persons( " 001 " , " 002 " , " 003 " );
            
// 正向输出
             foreach  ( string  s  in  p.InOrder)
            {
                Console.WriteLine(s);
            }
            
// 反序输出
             foreach  ( string  s  in  p.Reverse)
            {
                Console.WriteLine(s);
            }

        }

 

转载于:https://www.cnblogs.com/hubcarl/archive/2010/04/07/1706370.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值