主类:
public class InfiniteList<T> : IEnumerable<T> {
public List<T> SourceList { get; }
int start { get; }
public int Step { get; set; } = 1;
public InfiniteList(IEnumerable<T> source) : this(0, source) {
}
public InfiniteList(int start, IEnumerable<T> source) {
this.start = Math.Max(Math.Min(start, source.Count()), -1);
SourceList = new List<T>(source);
}
public InfiniteEnumerator<T> GetInfiniteEnumerator() {
return new InfiniteEnumerator<T>(this, start);
}
public IEnumerator<T> GetEnumerator() {
return GetInfiniteEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
}
迭代类:
public class InfiniteEnumerator<T> : IEnumerator<T> {
InfiniteList<T> list;
int start;
public int Index { get; set; }
public int Step { get; set; }
public InfiniteEnumerator(InfiniteList<T> source, int start) {
list = source;
Index = start - source.Step;
this.start = start;
Step = source.Step;
}
public T Current {
get { return list.SourceList[Index]; }
}
object IEnumerator.Current {
get { return Current; }
}
public void Dispose() {
}
public bool MoveNext() {
if (list.SourceList.Count == 0) {
return false;
}
if (Step == 0) {
return false;
}
Index += Step;
while (Index > list.SourceList.Count - 1) {
Index -= list.SourceList.Count;
}
while (Index < 0) {
Index += list.SourceList.Count;
}
return true;
}
public void Reset() {
Index = start;
}
}