(更新为显示常规列表类)这是一个可用于特殊列表类的类,它在到达最后一个元素时循环(循环到第一个项目):
public class ListCycle: IList { int curIndex = -1; List list; int nMax; public ListCycle(int n) { list = new List (n); nMax = n; } /// returns the current index we are in the list public int CurIndex { get { return curIndex; } } public int IndexOf(T item) { return list.IndexOf(item); } public bool Contains(T item) { return list.Contains(item); } public int Count { get { return list.Count; } } public bool IsReadOnly { get { return false; } } public IEnumeratorGetEnumerator() { return list.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return list.GetEnumerator(); } public T this[int index] { get { return list[index]; } set { list[index] = value; } } public void Add(T item) { curIndex++; if (curIndex >= nMax) curIndex = 0; if (curIndex < list.Count) list[curIndex] = item; else list.Add(item); } public void Clear() { list.Clear(); curIndex = -1; } //other mehods/properties for IList ... public void Insert(int index, T item) { throw new NotImplementedException(); } public bool Remove(T item) { throw new NotImplementedException(); } public void RemoveAt(int index) { throw new NotImplementedException(); } public void CopyTo(T[] array, int arrayIndex) { throw new NotImplementedException(); } }
用法很简单:
var list = new ListCycle(10); //fill the list for (int i = 0; i < 10; i++) { list.Add(i); } //now list is: // 0, 1, 2, 3, ... //add more items will start from first list.Add(100); //overrides first item list.Add(101); //overrides second item //now list is: // 100, 101, 2, 3, ...