C#高级程序设计(七)——迭代
.NET使用IEnumerator接口和IEnumerable接口(以及它们的泛型版本)实现迭代器模式,迭代是LINQ的核心。
接口定义如下:
[csharp]
public inte易做图ce IEnumerable
{
IEnumerator GetEnumerator();
}
public inte易做图ce IEnumerator
{
object Current { get; }
bool MoveNext();
void Reset();
}
public inte易做图ce IEnumerable<out T> : IEnumerable
{
IEnumerator<T> GetEnumerator();
}
public inte易做图ce IEnumerator<out T> : IDisposable, IEnumerator
{
T Current { get; }
}
一、C#1实现迭代方式
C#1通过实现接口实现迭代,下面是一个例子,可以指定起始的顺序来迭代集合,其中的一些注意点在注释中有所体现。
[csharp]
public class IterationSample : IEnumerable<string>
{
string[] values;
int startingPoint;
public IterationSample(string[] values, int startingPoint)
{
this.values = values;
this.startingPoint = startingPoint;
}
public IEnumerator<string> GetEnumerator()
{
// This is important to return a new instance of iterator
// so that each foreach loop will have its own iterator.
return new IterationSampleIterator(this);
}
// Class that implement IEnumerable<T> must also implement IEnumerable,
// here is a workaround to implement GetEnumerator method that defined
// in both IEnumerable<T> and IEnumerable.
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
// Inner class can access to private members of its parent class.
class IterationSampleIterator : IEnumerator<string>
{
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;
}
object IEnumerator.Current
{
get { return Current; }
}
public string 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;
}
public void Dispose()
{
}
}&
补充:软件开发 , C# ,