为什么我要使用的foreach,而不是为(INT I = 0; I<长度;我++)的循环? [英] Why should I use foreach instead of for (int i=0; i<length; i++) in loops?

查看:337
本文介绍了为什么我要使用的foreach,而不是为(INT I = 0; I<长度;我++)的循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是循环在C#中的冷静的方式和Java是使用的foreach而不是C风格的for循环。

It seems like the cool way of looping in C# and Java is to use foreach instead of C style for loops.

还有一个原因是我为什么要preFER这种风格在C形式?

Is there a reason why I should prefer this style over the C style?

我在这两种情况下特别感兴趣,但是当你需要解释你的观点,请处理尽可能多的情况下。

I'm particularly interested in these two cases, but please address as many cases as you need to explain your points.

  • 我想在列表中的每个项目执行的操作。
  • 在我寻找列表中的一个项目,想退出时,该项目被发现。

推荐答案

两个主要的原因,我能想到的是:

Two major reasons I can think of are:

1)抽象层从底层的容器类型。这意味着,例如,你不必改变code,它遍历容器中的所有物品,当你改变容器 - 你指定的目标的这样做的每个项目中的容器,而不是的表示的。

1) It abstracts away from the underlying container type. This means, for example, that you don't have to change the code that loops over all the items in the container when you change the container -- you're specifying the goal of "do this for every item in the container", not the means.

2)它消除掉接一个错误的可能性。

2) It eliminates the possibility of off-by-one errors.

在对列表中的每个项目执行操作方面,它很直观,只是说:

In terms of performing an operation on each item in a list, it's intuitive to just say:

for(Item item: lst)
{
  op(item);
}

这完全EX presses的意图给读者,而不是手工做的东西与迭代器。同上,用于搜索项目。

It perfectly expresses the intent to the reader, as opposed to manually doing stuff with iterators. Ditto for searching for items.

这篇关于为什么我要使用的foreach,而不是为(INT I = 0; I<长度;我++)的循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆