C# 自定义类型实现foreach 迭代
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace Foreach
{
class Program
{
static void Main(string[] args)
{
person[] persons = new person[]{
new person("aaa",20),
new person("bbb",21),
new person("ccc",22),
};
People peopleList = new People(persons);
foreach (var item in peopleList)
{
Console.WriteLine(item);
}
Console.ReadLine();
//person p = new person("aaa", 12); //调用了重写的函数方法
//Console.WriteLine(p.ToString());
}
}
public class person
{
string Name;
int Age;
public person(string name,int age)
{
Name = name;
this.Age = age;
}
public override string ToString()
//重写ToString()方法
{
return "Name:" + this.Name + "\tAge:" + this.Age;
}
}
public class PeopleEnum : System.Collections.IEnumerator
{
private person[] _people; //要控制的people
int postion = -1;
public PeopleEnum(person[] list)
{
_people = list;
}
public object Current
{
//get { throw new NotImplementedException(); }
get {
return _people[postion];
}
}
public bool MoveNext()
{
//throw new NotImplementedException();
postion++;
return (postion < _people.Length);
}
public void Reset()
{
//throw new NotImplementedException();
postion = -1;
}
}
public class People : IEnumerable
{
private person[] _people;
public People(person[] pArray)
{
_people = new person[pArray.Length];
for (int i = 0; i < pArray.Length; i++)
{
_people[i] = pArray[i];
}
}
public IEnumerator GetEnumerator()
{
//throw new NotImplementedException();
return new PeopleEnum(_people);
}
}
}
本文来自博客园,作者:至道中和,转载请注明原文链接:https://www.cnblogs.com/voidobject/archive/2012/09/19/3975496.html