for和foreach循环之间的区别 [英] Difference between for and foreach loop

查看:92
本文介绍了for和foreach循环之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for和foreach循环之间有什么区别。哪一个更方便使用?你能用例子解释一下。

解决方案

这取决于你在做什么,你需要什么。

如果你在迭代通过一组项目,并不关心索引值,然后foreach更方便,更容易编写和更安全:你不能得到错误的项目数。

如果你需要处理例如,集合中的每一个项目,或者以相反的顺序处理它们,然后for循环是唯一实用的方法。



最大的区别在于foreach循环依次处理集合中每个元素的实例,而for循环可以处理任何数据,并且不仅限于集合元素。这意味着for循环可以修改集合 - 这是非法的并且会在foreach循环中导致错误。



有关更多详细信息,请参阅MSDN:foreach [ ^ ]和 MSDN:for [ ^ ]


请参阅链接



http://www.c-sharpcorner.com/interviews/answer/2147/ [ ^ ]

http://stackoverflow.com/questions/10 929586 / for-fore-and-foreach 之间的差异[ ^ ]


访问这里..



FOREACH Vs. FOR(C#) [ ^

What is the difference between for and foreach loop. Which one is more convenient to use? Can you please explain it with example.

解决方案

It depends on what you are doing, and what you need.
If you are iterating through a collection of items, and do not care about the index values then foreach is more convenient, easier to write and safer: you can't get the number of items wrong.
If you need to process every second item in a collection for example, or process them ion the reverse order, then a for loop is the only practical way.

The biggest differences are that a foreach loop processes an instance of each element in a collection in turn, while a for loop can work with any data and is not restricted to collection elements alone. This means that a for loop can modify a collection - which is illegal and will cause an error in a foreach loop.

For more detail, see MSDN : foreach[^] and MSDN: for[^]


Please refer the link

http://www.c-sharpcorner.com/interviews/answer/2147/[^]
http://stackoverflow.com/questions/10929586/what-is-the-difference-between-for-and-foreach[^]


visit Here..

FOREACH Vs. FOR (C#)[^]


这篇关于for和foreach循环之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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