如何实现foreach

1:Net 1.1
using System.Collections;
using System;
public class Persons : IEnumerable
{
    
public string[] p_names;
    
public Persons(params string[] names)
    
{
        p_names
=new string[names.Length];
        names.CopyTo(p_names, 
0);
    }

    
public string this[int idx]
    
{
        
get return p_names[idx]; }
        
set { p_names[idx] = value; }
    }

    
public int Length
    
{
        
get return p_names.Length; }
    }

    
IEnumerable 成员
}

public class PersonsIterator : IEnumerator
{
    
private Persons _person;
    
private int idx;
    
public PersonsIterator(Persons person)
    
{
        
this._person = person;
        
this.idx = -1;
    }

    
IEnumerator 成员
}

class App
{
    
static void Main()
    
{
        IEnumerable persons 
= new Persons("Roboht","xinsoft","Spiderman");
        IEnumerator iterator 
= persons.GetEnumerator();
        
int i=0;
        
while(iterator.MoveNext())
        
{
            Console.WriteLine(
"persons[{0}] is {1}", i, iterator.Current);
            i
++;
        }

        Console.Read();
    }

}
2:Net2.0
public class Persons : IEnumerable
{
    
string[] m_Names;

    
public Persons(params string[] Names)
    
{
        m_Names 
= new string[Names.Length];

        Names.CopyTo(m_Names, 
0);
    }


    
public IEnumerator GetEnumerator()
    
{
        
foreach (string s in m_Names)
        
{
            
yield return s;
        }

    }

}


class Program
{
    
static void Main(string[] args)
    
{
        Persons arrPersons 
= new Persons("Michel""Christine""Mathieu""Julien");

        
foreach (string s in arrPersons)
        
{
            Console.WriteLine(s);
        }


        Console.ReadLine();
    }

}
posted @ 2008-05-28 10:28  roboth  阅读(489)  评论(0)    收藏  举报