2011-04-25 90 views
0

我创建了一个“反向itearator”对于一个LinkedList,现在我想用的扩展方法使用一个LinkedList:C#:访问反向枚举数

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

它不起作用。

我该怎么办?

+3

“不起作用”是什么意思?它会抛出一个错误,结果不是你所期望的吗?它不会编译? etc – taylonr 2011-04-25 14:44:26

+0

为什么一个'反向'枚举器,当你可以通过一个普通的枚举器向后迭代? – 2011-04-25 14:47:29

+0

@Cos,你如何通过普通的枚举器向后迭代? – svick 2011-04-25 14:51:03

回答

4

这不是foreach是如何工作的。任何实现IEnumerable接口的东西都必须重写GetEnumerator方法。这是由foreach调用的方法。如果你想向后枚举,你需要创建自己的IEnumerable并让它的GetEnumerator返回ReverseEnumerator。你可以用扩展方法来解决这个问题,只需要将扩展​​方法转换成一个ReverseLinkedList。

+0

感谢您的建议! – 2011-04-25 17:12:26