我的當前應用程序中有命令層次結構。C#:枚舉IEnumerable的循環枚舉
public interface ICommand
{
void Execute();
}
所以,有些命令是有狀態的,有些則不是。
我需要在命令執行過程中以循環的方式枚舉某些命令實現的IEnumerable。
public class GetNumberCommand : ICommand
{
public GetNumberCommand()
{
List<int> numbers = new List<int>
{
1, 2, 3
};
}
public void Execute()
{
// Circular iteration here.
// 1 => 2 => 3 => 1 => 2 => 3 => ...
}
public void Stop()
{
// Log current value. (2 for example)
}
}
Execute
不時被調用,所以需要存儲迭代狀態。
如何實現該圓形枚舉?
我發現兩種解決方案:
使用
IEnumerator<T>
接口。 它看起來像:if (!_enumerator.MoveNext()) { _enumerator.Reset(); _enumerator.MoveNext(); }
使用圓形
IEnumerable<T>
(yield
永遠相同的序列): Implementing A Circular Iterator。
也許有更多的方法來實現它。 你會推薦使用什麼?爲什麼?
在我的情況下,執行'不時被調用,所以有必要存儲迭代狀態。 –