为什么我应该在循环中使用 foreach 而不是 for (int i=0; i<length; i++) ? [英] Why should I use foreach instead of for (int i=0; i<length; i++) in loops?

查看:27
本文介绍了为什么我应该在循环中使用 foreach 而不是 for (int i=0; i<length; 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.

为什么我应该更喜欢这种风格而不是 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) 它从底层容器类型中抽象出来.这意味着,例如,当您更改容器时,您不必更改循环遍历容器中所有项目的代码——您指定的目标是为容器中的每个项目",而不是意味着.

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);
}

它完美地向读者表达了意图,而不是用迭代器手动做事.搜索项目同上.

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

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

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