可以通过foreach向后迭代吗? [英] Possible to iterate backwards through a foreach?
问题描述
我知道我可以使用 for
语句并达到相同的效果,但是我可以通过 C# 中的 foreach
循环向后循环吗?
I know I could use a for
statement and achieve the same effect, but can I loop backwards through a foreach
loop in C#?
推荐答案
在使用列表(直接索引)时,您无法像使用 for
循环那样高效.
When working with a list (direct indexing), you cannot do it as efficiently as using a for
loop.
这通常意味着,当您能够使用 for
循环时,这可能是此任务的正确方法.另外,由于 foreach
是按顺序实现的,因此构造本身是为表达独立于元素索引和迭代顺序的循环而构建的,这在 并行编程.我认为依赖于顺序的迭代不应该使用foreach
进行循环.
Which generally means, when you are able to use a for
loop, it's likely the correct method for this task. Plus, for as much as foreach
is implemented in-order, the construct itself is built for expressing loops that are independent of element indexes and iteration order, which is particularly important in parallel programming. It is my opinion that iteration relying on order should not use foreach
for looping.
这篇关于可以通过foreach向后迭代吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!