C#循环语句总结

前言

正所谓磨刀不误砍柴工,C#上位机软件开发能力的提升离不开对C#语法的精通,本文接着讲解C#语法知识中的循环语句,在C#程序开发中我们经常会用到各种循环语句,常见的有for循环、while循环,本文就是对C#中用到的各种循环语句进行了总结,内容如下:

1、for循环

1.1 每次加1递增循环

每次增加1,循环10次

复制代码
    for(int i=0;i<10;i++)
    {
        Console.WriteLine(i);
    }

输出:

csharp 复制代码
0
1
2
3
4
5
6
7
8
9

1.2 设置指定步长的递增循环

每次增加2,可设置步长,循环5次

csharp 复制代码
 int stepAdd = 2;
        for (int i = 0; i < 10; i=i+ stepAdd)
        {
            Console.WriteLine(i);
        }

输出:

csharp 复制代码
0
2
4
6
8

1.3 递减循环

每次减2,可设置步长,循环5次

复制代码
int stepDec = 2;
    for (int i = 10; i >0; i = i - stepDec)
    {
        Console.WriteLine(i);
    }

输出:

csharp 复制代码
10
8
6
4
2

2、while循环

2.1 搭配break语句跳出循环

break语句执行时,直接跳出while循环。

csharp 复制代码
  int count = 0;
        while (true )
        {
            count = count + 1;
            Console.WriteLine(count);
            if (count >=10)
            {
                break;//使用break跳出大的循环语句
            }
        }

输出:

csharp 复制代码
1
2
3
4
5
6
7
8
9
10

2.2 搭配continue语句不执行当前循环后面语句

continue执行时,continue语句后面的代码都不执行,然后会重新跳到 while (true)这里。

从输出结果可以看出count等于5的时候没有输出

复制代码
count = 0;
    while (true)
    {
        count = count + 1;
        if (count == 5)
        {
            continue;//使用continue不执行本次循环后面的语句
        }

        if (count >= 10)
        {
            break;//使用break跳出大的循环语句
        }
        Console.WriteLine(count);
    }

输出:

csharp 复制代码
1
2
3
4
6
7
8
9

3、do while循环

do while循环,先执行语句,然后判断是否继续执行循环

下面的代码中count < 10就执行循环,否则结束循环

csharp 复制代码
   count = 0;
        do
        {
            count = count + 1;
            Console.WriteLine(count);
        }
        while (count < 10);

输出:

csharp 复制代码
1
2
3
4
5
6
7
8
9
10

4、foreach循环

foreach循环,一般用于对集合对象的访问

csharp 复制代码
   List<int> ListTest = new List<int>();
        ListTest.Add(1);
        ListTest.Add(2);
        ListTest.Add(3);
        ListTest.Add(4);
        ListTest.Add(5);
        foreach (int item in ListTest)
        {
            Console.WriteLine(item);
        }

输出:

csharp 复制代码
1
2
3
4
5
相关推荐
我真的不会C2 分钟前
QT窗口相关控件及其属性
开发语言·qt
CodeCraft Studio3 分钟前
Excel处理控件Aspose.Cells教程:使用 Python 在 Excel 中进行数据验
开发语言·python·excel
火柴盒zhang8 分钟前
websheet之 编辑器
开发语言·前端·javascript·编辑器·spreadsheet·websheet
景天科技苑16 分钟前
【Rust】Rust中的枚举与模式匹配,原理解析与应用实战
开发语言·后端·rust·match·enum·枚举与模式匹配·rust枚举与模式匹配
阿让啊21 分钟前
C语言中操作字节的某一位
c语言·开发语言·数据结构·单片机·算法
椰羊~王小美26 分钟前
LeetCode -- Flora -- edit 2025-04-25
java·开发语言
孞㐑¥1 小时前
C++11介绍
开发语言·c++·经验分享·笔记
旦莫1 小时前
Python 教程:我们可以给 Python 文件起中文名吗?
开发语言·python
꧁坚持很酷꧂2 小时前
配置Ubuntu18.04中的Qt Creator为中文(图文详解)
开发语言·qt·ubuntu
不当菜虚困2 小时前
JAVA设计模式——(四)门面模式
java·开发语言·设计模式