public interface IEnumerable
{
IEnumerator GetEnumerator();
}
public interface IEnumerator : IDisposable
{
T Current { get; }
bool MoveNext();
}
// 無 Reset(),由新實例替代
public class CityCollection : IEnumerable
{
string[] _cities = {"New York","Paris","London"};
public IEnumerator GetEnumerator() => new CityEnumerator(this);
class CityEnumerator : IEnumerator
{
CityCollection _collection;
int _index = -1;
public CityEnumerator(CityCollection c) { _collection = c; }
public bool MoveNext() => ++_index < _collection._cities.Length;
public string Current
{
get
{
if (_index == -1) throw new InvalidOperationException();
return _collection._cities[_index];
}
}
public void Dispose() {}
}
}
// 原始
foreach (string city in cities) Console.WriteLine(city);
// 展開
IEnumerator e = cities.GetEnumerator();
try
{
while (e.MoveNext())
{
string city = e.Current;
Console.WriteLine(city);
}
}
finally { e.Dispose(); }
需精確控制迭代流程(如雙指針、合併兩序列)時,可直接操作 `MoveNext`/`Current`,不依賴 `foreach` 語法糖。