在C#中,双向枚举器是一种可以在双向(前后)遍历集合的枚举器。在C#中,可以使用IEnumerator<T>
接口来实现双向枚举器。
以下是一个简单的双向枚举器示例:
public class BiDirectionalEnumerator<T> : IEnumerator<T>
{
private readonly List<T> _items;
private int _currentIndex;
private readonly int _startIndex;
public BiDirectionalEnumerator(List<T> items, int startIndex)
{
_items = items;
_currentIndex = startIndex;
_startIndex = startIndex;
}
public bool MoveNext()
{
if (_currentIndex < _items.Count - 1)
{
_currentIndex++;
return true;
}
return false;
}
public bool MovePrevious()
{
if (_currentIndex > 0)
{
_currentIndex--;
return true;
}
return false;
}
public void Reset()
{
_currentIndex = _startIndex;
}
public T Current
{
get { return _items[_currentIndex]; }
}
object IEnumerator.Current
{
get { return Current; }
}
public void Dispose()
{
}
}
在这个示例中,我们定义了一个泛型的双向枚举器BiDirectionalEnumerator<T>
,它实现了IEnumerator<T>
接口,并添加了MovePrevious()
方法来实现双向遍历。
使用这个双向枚举器的示例代码如下:
var items = new List<int> { 1, 2, 3, 4, 5 };
var enumerator = new BiDirectionalEnumerator<int>(items, 0);
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current);
}
while (enumerator.MovePrevious())
{
Console.WriteLine(enumerator.Current);
}
在这个示例中,我们创建了一个包含5个整数的列表,并使用BiDirectionalEnumerator<T>
来遍历这个列表。首先,我们使用MoveNext()
方法来遍历列表中的每个元素,然后再使用MovePrevious()
方法来遍历列表中的每个元素。
需要注意的是,在使用双向枚举器时,必须确保在调用MovePrevious()
方法之前已经调用了MoveNext()
方法,否则MovePrevious()
方法将返回false
。同样地,在使用MoveNext()
方法之前必须先调用MovePrevious()
方法,否则MoveNext()
方法将返回false
。
云+社区技术沙龙[第6期]
腾讯云数据湖专题直播
云+社区沙龙online [国产数据库]
云+社区沙龙online第5期[架构演进]
腾讯数字政务云端系列直播
云+社区技术沙龙[第17期]
领取专属 10元无门槛券
手把手带您无忧上云