C# for/foreach 循环 | C# 循环

返回到:C# 循环

一个 for 循环是一个允许您编写一个执行特定次数的循环的重复控制结构。

语法

C# 中 for 循环的语法:

for ( init; condition; increment )
{
   statement(s);
}

下面是 for 循环的控制流:

  1. init 会首先被执行,且只会执行一次。这一步允许您声明并初始化任何循环控制变量。您也可以不在这里写任何语句,只要有一个分号出现即可。
  2. 接下来,会判断 condition。如果为真,则执行循环主体。如果为假,则不执行循环主体,且控制流会跳转到紧接着 for 循环的下一条语句。
  3. 在执行完 for 循环主体后,控制流会跳回上面的 increment 语句。该语句允许您更新循环控制变量。该语句可以留空,只要在条件后有一个分号出现即可。
  4. 条件再次被判断。如果为真,则执行循环,这个过程会不断重复(循环主体,然后增加步值,再然后重新判断条件)。在条件变为假时,for 循环终止。

流程图

C# for/foreach 循环 | C# 循环

实例

using System;

namespace Loops
{
   
    class Program
    {
        static void Main(string[] args)
        {
            /* for 循环执行 */
            for (int a = 10; a < 20; a = a + 1)
            {
                Console.WriteLine("a 的值: {0}", a);
            }
            Console.ReadLine();
        }
    }
}

当上面的代码被编译和执行时,它会产生下列结果:

a 的值: 10
a 的值: 11
a 的值: 12
a 的值: 13
a 的值: 14
a 的值: 15
a 的值: 16
a 的值: 17
a 的值: 18
a 的值: 19

foreach

C# 也支持 foreach 循环,使用 foreach 可以迭代数组或者一个集合对象。

C# 的 foreach 循环可以用来遍历集合类型,例如数组、列表、字典等。它是一个简化版的 for 循环,使得代码更加简洁易读。

以下是 foreach 循环的语法:

foreach (var item in collection)
{
    // 循环
}

collection 是要遍历的集合,item 是当前遍历到的元素。

以下实例有三个部分:

  • 通过 foreach 循环输出整型数组中的元素。
  • 通过 for 循环输出整型数组中的元素。
  • foreach 循环设置数组元素的计算器。
class ForEachTest
{
    static void Main(string[] args)
    {
        int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };
        foreach (int element in fibarray)
        {
            System.Console.WriteLine(element);
        }
        System.Console.WriteLine();


        // 类似 foreach 循环
        for (int i = 0; i < fibarray.Length; i++)
        {
            System.Console.WriteLine(fibarray[i]);
        }
        System.Console.WriteLine();


        // 设置集合中元素的计算器
        int count = 0;
        foreach (int element in fibarray)
        {
            count += 1;
            System.Console.WriteLine("Element #{0}: {1}", count, element);
        }
        System.Console.WriteLine("Number of elements in the array: {0}", count);
    }
}

输出结果为:

0
1
1
2
3
5
8
13

0
1
1
2
3
5
8
13

Element #1: 0
Element #2: 1
Element #3: 1
Element #4: 2
Element #5: 3
Element #6: 5
Element #7: 8
Element #8: 13
Number of elements in the array: 8

以下实例我们使用 foreach 来遍历一个列表:

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // 创建一个字符串列表
        List<string> myStrings = new List<string>();

        // 向列表添加一些字符串元素
        myStrings.Add("Google");
        myStrings.Add("Runoob");
        myStrings.Add("Taobao");

        // 使用 foreach 循环遍历列表中的元素
        foreach (string s in myStrings)
        {
            Console.WriteLine(s);
        }

        // 等待用户按下任意键后退出程序
        Console.ReadKey();
    }
}

当上面的代码被编译和执行时,它会产生下列结果:

Google
Runoob
Taobao

更多 foreach 内容可以参考:C# 中 foreach 遍历的用法

返回到:C# 循环

作者:terry,如若转载,请注明出处:https://www.web176.com/csharp_api/14069.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2023年3月23日
下一篇 2023年3月23日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注