实现一个迭代器必须实现IEnumerator
01.传统方式来实现自定义的迭代器
using System;
using System.Collections;
using System.Net.NetworkInformation;
using static System.Console;
namespace Interpreter
{
class Program
{
static void Main(string[] args)
{
Friends friends=new Friends();
foreach (Friend friend in friends)
{
WriteLine(friend.Name);
}
ReadKey();
}
}
class Friend
{
public string Name { get; set; }
public Friend(string name)
{
this.Name = name;
}
}
class Friends:IEnumerable
{
private Friend[] friendArray;
public Friends()
{
friendArray=new Friend[]
{
new Friend("张三"),
new Friend("李四"),
new Friend("王五"),
};
}
//索引器
public Friend this[int index]
{
get { return friendArray[index]; }
}
public int Count
{
get { return friendArray.Length; }
}
public IEnumerator GetEnumerator()
{
return new FriendIterator(this);
}
}
//自定义迭代器,实现 IEnumerator接口
class FriendIterator:IEnumerator
{
private readonly Friends friends;
private int index;
private Friend current;
public FriendIterator(Friends friends)
{
this.friends = friends;
index = 0;
}
public bool MoveNext()
{
if (index+1>friends.Count)
{
return false;
}
else
{
this.current = friends[index];
index++;
return true;
}
}
public void Reset()
{
index = 0;
}
public object Current
{
get
{
return this.current;
}
}
}
}
02.C#2.0的新特性简化迭代器的实现
using System;
using System.Collections;
using static System.Console;
namespace Interpreter2
{
class Program
{
static void Main(string[] args)
{
Friends friends=new Friends();
foreach (Friend friend in friends)
{
WriteLine(friend.Name);
}
ReadKey();
}
}
class Friend
{
public string Name { get; set; }
public Friend(string name)
{
this.Name = name;
}
}
class Friends:IEnumerable
{
private Friend[] friendarray;
public Friends()
{
friendarray = new Friend[]
{
new Friend("张三"),
new Friend("李四"),
new Friend("王五"),
};
}
public Friend this[int index]
{
get { return friendarray[index]; }
}
public int Count
{
get { return friendarray.Length; }
}
public IEnumerator GetEnumerator()
{
for (int index = 0; index < friendarray.Length; index++)
{
yield return friendarray[index];
}
}
}
}