C# for 和 foreach 和有什么不一样?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10929586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between for and foreach?
提问by Chandru A
What is the major difference between forand foreachloops?
for和foreach循环之间的主要区别是什么?
In which scenarios can we use forand not foreachand vice versa.
我们可以在哪些场景中使用for而不能使用,foreach反之亦然。
Would it be possible to show with a simple program?
可以用一个简单的程序显示吗?
Both seem the same to me. I can't differentiate them.
两者在我看来都是一样的。我无法区分它们。
回答by Femaref
You can use foreachif the object you want to iterate over implements the IEnumerableinterface. You need to use forif you can access the object only by index.
foreach如果要迭代的对象实现了IEnumerable接口,则可以使用。for如果只能通过索引访问对象,则需要使用。
回答by Dave Bish
a forloop is a construct that says "perform this operation n. times".
一个for循环是一个构造,说:“执行此操作ñ。时间”。
a foreachloop is a construct that says "perform this operation against eachvalue/object in this IEnumerable"
一个foreach循环是说,一个构建体“对执行此操作的每个在此IEnumerable的值/对象”
回答by Maziar Aboualizadehbehbahani
foreach is useful if you have a array or other IEnumerable Collection of data. but for can be used for access elements of an array that can be accessed by their index.
如果您有数组或其他 IEnumerable 数据集合,则 foreach 很有用。但 for 可用于访问可通过其索引访问的数组元素。
回答by Mario
I'll tryto answer this in a more general approach:
我将尝试以更一般的方法回答这个问题:
foreachis used to iterate over each element of a given set or list (anything implementing IEnumerable) in a predefined manner. You can't influence the exact order (other than skipping entries or canceling the whole loop), as that's determined by the container.
foreach用于以IEnumerable预定义的方式迭代给定集合或列表(任何实现)的每个元素。您不能影响确切的顺序(除了跳过条目或取消整个循环),因为这是由容器决定的。
foreach (String line in document) { // iterate through all elements of "document" as String objects
Console.Write(line); // print the line
}
foris just another way to write a loop that has code executed before entering the loop and once after every iteration. It's usually used to loop through code a given number of times. Contrary to foreachhere you're able to influence the current position.
for只是另一种编写循环的方法,该循环在进入循环之前和每次迭代之后都执行了一次代码。它通常用于循环代码指定次数。与foreach此处相反,您可以影响当前位置。
for (int i = 0, j = 0; i < 100 && j < 10; ++i) { // set i and j to 0, then loop as long as i is less than 100 or j is less than 10 and increase i after each iteration
if (i % 8 == 0) { // skip all numbers that can be divided by 8 and count them in j
++j
continue;
}
Console.Write(i);
}
Console.Write(j);
If possible and applicable, always use foreachrather than for(assuming there's some array index). Depending on internal data organisation, foreachcan be a lot faster than using forwith an index (esp. when using linked lists).
如果可能且适用,请始终使用foreach而不是for(假设有一些数组索引)。根据内部数据组织,foreach可以比使用for索引快得多(尤其是在使用链表时)。
回答by kallol
for loop:
for循环:
1) need to specify the loop bounds( minimum or maximum).
2) executes a statement or a block of statements repeatedly
until a specified expression evaluates to false.
Ex1:-
例1:-
int K = 0;
for (int x = 1; x <= 9; x++){
k = k + x ;
}
foreach statement:
foreach 语句:
1)do not need to specify the loop bounds minimum or maximum.
2)repeats a group of embedded statements for
a)each element in an array
or b) an object collection.
Ex2:-
例2:-
int k = 0;
int[] tempArr = new int[] { 0, 2, 3, 8, 17 };
foreach (int i in tempArr){
k = k + i ;
}
回答by Francesco Baruchelli
Everybody gave you the right answer with regard to foreach, i.e. it's a way to loop through the elements of something implementing IEnumerable.
每个人都给了你关于 foreach 的正确答案,即它是一种遍历实现 IEnumerable 的元素的方法。
On the other side, for is much more flexible than what is shown in the other answers. In fact, for is used to executes a block of statements for as long as a specified condition is true.
另一方面, for 比其他答案中显示的要灵活得多。事实上,for 用于在指定条件为真时执行语句块。
From Microsoft documentation:
来自微软文档:
for (initialization; test; increment)
statement
initialization Required. An expression. This expression is executed only once, before the loop is executed.
初始化 必需。一种表达。在执行循环之前,此表达式仅执行一次。
test Required. A Boolean expression. If test is true, statement is executed. If test if false, the loop is terminated.
测试要求。布尔表达式。如果 test 为真,则执行语句。如果测试为假,则循环终止。
increment Required. An expression. The increment expression is executed at the end of every pass through the loop.
增量 必需。一种表达。增量表达式在每次循环结束时执行。
statement Optional. Statement to be executed if test is true. Can be a compound statement.
声明 可选。如果 test 为真则执行的语句。可以是复合语句。
This means that you can use it in many different ways. Classic school examples are the sum of the numbers from 1 to 10:
这意味着您可以以多种不同的方式使用它。经典的学校例子是从 1 到 10 的数字之和:
int sum = 0;
for (int i = 0; i <= 10; i++)
sum = sum + i;
But you can use it to sum the numbers in an Array, too:
但是你也可以用它来对数组中的数字求和:
int[] anArr = new int[] { 1, 1, 2, 3, 5, 8, 13, 21 };
int sum = 0;
for (int i = 0; i < anArr.Length; i++)
sum = sum + anArr[i];
(this could have been done with a foreach, too):
(这也可以用 foreach 来完成):
int[] anArr = new int[] { 1, 1, 2, 3, 5, 8, 13, 21 };
int sum = 0;
foreach (int anInt in anArr)
sum = sum + anInt;
But you can use it for the sum of the even numbers from 1 to 10:
但是你可以用它来求从 1 到 10 的偶数之和:
int sum = 0;
for (int i = 0; i <= 10; i = i + 2)
sum = sum + i;
And you can even invent some crazy thing like this one:
你甚至可以发明一些像这样的疯狂东西:
int i = 65;
for (string s = string.Empty; s != "ABC"; s = s + Convert.ToChar(i++).ToString()) ;
Console.WriteLine(s);
回答by colonelclick
A for loop is useful when you have an indication or determination, in advance, of how many times you want a loop to run. As an example, if you need to perform a process for each day of the week, you know you want 7 loops.
当您预先知道或确定希望循环运行多少次时,for 循环很有用。例如,如果您需要为一周中的每一天执行一个流程,您就知道需要 7 个循环。
A foreach loop is when you want to repeat a process for all pieces of a collection or array, but it is not important specifically how many times the loop runs. As an example, you are formatting a list of favorite books for users. Every user may have a different number of books, or none, and we don't really care how many it is, we just want the loop to act on all of them.
foreach 循环是当您想要对集合或数组的所有部分重复一个过程时,但具体循环运行多少次并不重要。例如,您正在格式化用户最喜欢的书籍列表。每个用户可能拥有不同数量的书籍,或者没有,我们并不真正关心它有多少,我们只希望循环对所有书籍进行操作。
回答by sivasankar
simple difference between for and foreach
for 和 foreach 之间的简单区别
for loop is working with values.it must have condition then increment and intialization also.you have to knowledge about 'how many times loop repeated'.
foreach is working with objects and enumaretors. no need to knowledge how many times loop repeated.
回答by polkduran
foreachis almost equivalent to :
foreach几乎相当于:
var enumerator = list.GetEnumerator();
var element;
while(enumerator.MoveNext()){
element = enumerator.Current;
}
and in order to implemetn a "foreach" compliant pattern, this need to provide a class that have a method GetEnumerator()which returns an object that have a MoveNext()method, a Reset()method and a Currentproperty.
并且为了实现“foreach”兼容模式,这需要提供一个具有方法GetEnumerator()的类,该方法返回具有MoveNext()方法、Reset()方法和Current属性的对象。
Indeed, you do not need to implement neither IEnumerable nor IEnumerator.
实际上,您不需要实现 IEnumerable 和 IEnumerator。
Some derived points:
一些派生点:
foreachdoes not need to know the collection length so allows to iterate through a "stream" or a kind of "elements producer".foreachcalls virtual methods on the iterator (the most of the time) so can perform less well thanfor.
foreach不需要知道集合长度,因此允许迭代“流”或一种“元素生产者”。foreach在迭代器上调用虚拟方法(大部分时间),因此性能不如for.
回答by sireesh
The foreach statement repeats a group of embedded statements for each element in an array or an object collection that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable interface. The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.
foreach 语句为实现 System.Collections.IEnumerable 或 System.Collections.Generic.IEnumerable 接口的数组或对象集合中的每个元素重复一组嵌入语句。foreach 语句用于遍历集合以获取您想要的信息,但不能用于从源集合中添加或删除项目以避免不可预测的副作用。如果您需要从源集合中添加或删除项目,请使用 for 循环。

