using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Data.Common;
using System.Data;
using System.Security.Util;
using System.Text.RegularExpressions;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
Person[] ps = { new Person("a", 1), new Person("b", 2), new Person("c", 3) };
People p = new People(ps);
foreach (Person item in p)
{
Console.WriteLine("name={0},age={1}",item.Name,item.Age);
}
Console.Read();
}
}
class Person
{
public string Name;
public int Age;
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
class PersonEnum : IEnumerator
{
Person []ps;
public PersonEnum(Person[]ps)
{
this.ps=ps;
}
int position = -1;
public void Reset (){ position=-1;}
public bool MoveNext() { ++position; return position < ps.Length; }
public object Current { get { return ps[position];} }
}
class People:IEnumerable
{
Person[] ps;
public People(Person[]ps)
{
this.ps = ps;
}
public IEnumerator GetEnumerator()
{
return new PersonEnum(ps);
}
}
}
上边例子中,如果将Main中的代码换成下边这样子也能实现foreach啊,为什么要像上面这样写呢?
Person[] ps = { new Person("a", 1), new Person("b", 2), new Person("c", 3) };
foreach (Person item in ps)
{
Console.WriteLine("name={0},age={1}",item.Name,item.Age);
}
Console.Read();
- 4 回答
- 0 关注
- 388 浏览
添加回答
举报
0/150
提交
取消