using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _6_1
{
class Program
{
static void Main(string[] args)
{
object[] values = { "a", "b", "c", "d", "e" };
IterationSample conllection = new IterationSample(values, 3);
foreach (string x in conllection)
{
Console.WriteLine(x);
}
Console.ReadKey();
}
}
class IterationSample : IEnumerable
{
object[] values;
int startingPoint;
public IterationSample(object[] values, int startingPoint)
{
this.values = values;
this.startingPoint = startingPoint;
}
public IEnumerator GetEnumerator()
{
//throw new NotImplementedException();
return new IterationSampleIterator(this);
}
//class IterationSampleIterator : IEnumerator
//{
// IterationSample parent;
// int position;
// internal IterationSampleIterator(IterationSample parent)
// {
// this.parent = parent;
// position = -1;
// }
// public bool moveNext()
// {
// if (position != parent.values.Length)
// {
// position++;
// }
// return position < parent.values.Length;
// }
// public object Current
// {
// get
// {
// if (position == -1 || position == parent.values.Length)
// {
// throw new InvalidOperationException();
// }
// int index = position + parent.startingPoint;
// index = index % parent.values.Length;
// return parent.values[index];
// }
// }
// public void reset()
// {
// position = -1;
// }
//}
class IterationSampleIterator : IEnumerator
{
IterationSample parent;
int position;
internal IterationSampleIterator(IterationSample parent)
{
this.parent = parent;
position = -1;
}
public bool MoveNext()
{
if (position != parent.values.Length)
{
position++;
}
return position < parent.values.Length;
}
public object Current
{
get
{
if (position == -1 ||
position == parent.values.Length)
{
throw new InvalidOperationException();
}
int index = (position + parent.startingPoint);
index = index % parent.values.Length;
return parent.values[index];
}
}
public void Reset()
{
position = -1;
}
}
}
}
C#2中实现迭代器
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _6_4
{
class Program
{
static void Main(string[] args)
{
}
public IEnumerator GetEnumerator() {
int staringPoint=1;
object [] values={"a","b","c","d","e"};
for (int index = 0; index < values.Length;index++ ) {
yield return values[(index + staringPoint) % values.Length];
}
}
}
}