C#: Access a reverse enumerator for a linkedlist
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?
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.
精彩评论