0

我为 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>())

它不起作用。

我应该怎么办?

4

1 回答 1

4

这不是 foreach 的工作方式。任何实现 IEnumerable 接口的东西都必须重写 GetEnumerator 方法。这是foreach调用的方法。如果要向后枚举,则需要创建自己的 IEnumerable 并让它的 GetEnumerator 返回 ReverseEnumerator。您仍然可以使用扩展方法来实现这一点,只需让扩展方法将您的 LinkedList 转换为 ReverseLinkedList。

于 2011-04-25T14:48:00.247 回答