for和foreach有什么区别?

Cha*_*u A 18 c# foreach for-loop

forforeach循环之间的主要区别是什么?

在哪些场景中我们可以使用for而不是foreach,反之亦然.

是否可以用简单的程序来展示?

两者对我来说都是一样的.我无法区分它们.

Dav*_*ish 20

一个for循环是一个构造,说:"执行此操作ñ.时间 ".

一个foreach循环是说,一个构建体"对执行此操作的每个在此IEnumerable的值/对象"

  • `for`不是真正的"n.次",而是"当满足这个条件时",这通常是一个简单的计数器检查.并且你实际上并不需要'IEnumerable`用于`foreach`,但实际上:它在语义上是"依次获取每个项目"API. (17认同)

Fem*_*ref 12

foreach如果要迭代的对象实现IEnumerable接口,则可以使用.for如果只能通过索引访问对象,则需要使用.

  • *技术上*`IEnumerable`接口不是`foreach`的先决条件,但几乎就是这样; p (5认同)

Mar*_*rio 11

我将尝试用更通用的方法回答这个问题:

foreach用于以IEnumerable预定义的方式迭代给定集合或列表(实现任何内容)的每个元素.您不能影响确切的顺序(跳过条目或取消整个循环除外),因为这是由容器决定的.

foreach (String line in document) { // iterate through all elements of "document" as String objects
    Console.Write(line); // print the line
}
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

如果可能且适用,请始终使用foreach而不是for(假设有一些数组索引).根据内部数据组织,foreach可能比使用for索引要快得多(特别是在使用链接列表时).


Fra*_*lli 5

每个人都给出了关于foreach的正确答案,即它是一种循环实现IEnumerable的元素的方法.

另一方面,因为它比其他答案中显示的更灵活.实际上,只要指定的条件为真,就用于执行语句块.

来自Microsoft文档:

for (initialization; test; increment)
     statement
Run Code Online (Sandbox Code Playgroud)

初始化必需.一种表达.在执行循环之前,此表达式仅执行一次.

测试必需.布尔表达式.如果test为true,则执行语句.如果测试为false,则循环终止.

增量必需.一种表达.递增表达式在每次循环结束时执行.

声明可选.如果测试为真,则执行语句.可以是复合语句.

这意味着您可以通过多种不同方式使用它.经典学校示例是1到10之间的数字之和:

int sum = 0;
for (int i = 0; i <= 10; i++)
    sum = sum + i;
Run Code Online (Sandbox Code Playgroud)

但是你也可以使用它来对数组中的数字求和:

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];
Run Code Online (Sandbox Code Playgroud)

(这也可以用foreach完成):

int[] anArr = new int[] { 1, 1, 2, 3, 5, 8, 13, 21 };
int sum = 0;
foreach (int anInt in anArr)
    sum = sum + anInt;
Run Code Online (Sandbox Code Playgroud)

但是你可以用它来表示从1到10的偶数:

int sum = 0;
for (int i = 0; i <= 10; i = i + 2)
    sum = sum + i;
Run Code Online (Sandbox Code Playgroud)

你甚至可以发明一些像这样的疯狂的东西:

int i = 65;
for (string s = string.Empty; s != "ABC"; s = s + Convert.ToChar(i++).ToString()) ;
    Console.WriteLine(s);
Run Code Online (Sandbox Code Playgroud)