C#:访问链表的反向枚举器
我已经为 LinkedList 创建了一个“反向迭代器”,现在我想将它与扩展方法一起使用:
public static class LinkedListExtensionMethods
{
public static IEnumerator GetReverseEnumerator<T>(this LinkedList<T> linkedList)
{
return new LinkedListReverseEnumerator<T>(linkedList);
}
public static IEnumerator<T> GetReverseGenericEnumerator<T>(this LinkedList<T> linkedList)
{
return new LinkedListReverseEnumerator<T>(linkedList);
}
}
但是如果我写:
foreach (ICommand command in _CompoundDoCollection.GetReverseEnumerator<ICommand>())
它不起作用。
我应该怎么办?
I've created a "reverse itearator" for a LinkedList, now I would like to use it with an extension method:
public static class LinkedListExtensionMethods
{
public static IEnumerator GetReverseEnumerator<T>(this LinkedList<T> linkedList)
{
return new LinkedListReverseEnumerator<T>(linkedList);
}
public static IEnumerator<T> GetReverseGenericEnumerator<T>(this LinkedList<T> linkedList)
{
return new LinkedListReverseEnumerator<T>(linkedList);
}
}
However if I write:
foreach (ICommand command in _CompoundDoCollection.GetReverseEnumerator<ICommand>())
it doesn't work.
What should I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
foreach 不是这样工作的。任何实现 IEnumerable 接口的东西都必须重写 GetEnumerator 方法。这是foreach调用的方法。如果你想向后枚举,你需要创建自己的 IEnumerable 并让它的 GetEnumerator 返回 ReverseEnumerator。您仍然可以使用扩展方法来实现此目的,只需让扩展方法将您的 LinkedList 转换为 ReverseLinkedList 即可。
That's not how foreach works. Anything that implements the IEnumerable interface must override the GetEnumerator method. This is the method called by foreach. If you want to enumerate backwards, you need to make your own IEnumerable and have it's GetEnumerator return the ReverseEnumerator. You can stil to this with a extension method, just have the extension method convert your LinkedList to a ReverseLinkedList.