微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

vb.net – 是可能做一个For …每个循环向后?

我不相信这是可能的常规方法,但类似这样详细的代码
For Each s As String In myStringList Step -1
    //' Do stuff here
Next

我可能必须反转myString对象之前一个常规的For..Each循环,正确吗?

我认为答案中引用的文档是非常误导的。 For Each的顺序由它所调用的集合(即其实现的IEnumerable / IEnumerable< T>)定义,但这不同于在顺序很重要时不应该使用它。许多集合(例如数组,List< T>等)总是以“自然”顺序。

文档的一部分暗示了这一点:

Traversal Order. When you execute a
For Each…Next loop,traversal of the
collection is under the control of the
enumerator object returned by the
GetEnumerator method. The order of
traversal is not determined by Visual
Basic,but rather by the MoveNext
method of the enumerator object. This
means that you might not be able to
predict which element of the
collection is the first to be returned
in element,or which is the next to be
returned after a given element.

这并不是说它不能被依赖 – 它可以依靠,如果你知道,你正在迭代的集合将产生所需的顺序的结果。这不是它会随机挑选元素。关于IEnumerable / IEnumerable< T>的行为在该页面上明确定义。

可预测的顺序的最重要的例外是字典和集合,它们是自然无序的。

要反转IEnumerable< T>,使用Enumerable.Reverse – 但是如果你需要反向迭代通过位置索引的集合(例如数组或List< T>),那么使用For循环开始在结束和向后工作。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐