.NET 帮助

C# 循环(开发者使用方法)

在本综合教程中,我们将涵盖所有您需要知道的内容,以便在public static void Main方法中开始使用for循环。 我们将探讨 for 循环、循环变量、循环体、迭代变量、内循环和外循环、无限循环、布尔表达式、嵌套循环等。 让我们开始吧!

for Loops 入门

for循环是一种C#中的循环类型,专为您确切知道要迭代多少次的情况而设计。 C#中for循环的语法如下代码块所示:

    for (initialization; condition; increment)
    {
        // Loop body
    }
    for (initialization; condition; increment)
    {
        // Loop body
    }
initialization
Do While condition
		' Loop body
	increment
Loop
$vbLabelText   $csharpLabel

让我们来分析一下 for 循环的组成部分:

  1. 初始化:这是声明和初始化循环变量或迭代变量的地方。

  2. 条件:一个布尔/条件表达式,用于决定循环是否应继续多次执行语句。

  3. 增量:此语句在每次迭代后更新迭代变量。

静态 Void 主变量和循环变量

在 C# 中,static void Main 方法或 static void Main(String []args) 是应用程序的入口点。 这是您的程序开始执行的地方。 这是一个关于如何在static void Main方法内使用for循环的示例:

    using System;

    class Program
    {
        static void Main()
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("This is the first for loop!");
            }
        }
    }
    using System;

    class Program
    {
        static void Main()
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("This is the first for loop!");
            }
        }
    }
Imports System

	Friend Class Program
		Shared Sub Main()
			For i As Integer = 0 To 4
				Console.WriteLine("This is the first for loop!")
			Next i
		End Sub
	End Class
$vbLabelText   $csharpLabel

在此示例中,循环变量int i被初始化为0,充当变量。 循环将继续执行,只要i小于5。 在每次迭代之后,递增操作i++会将i的值增加1。

探索嵌套循环

C#中的嵌套循环是指位于其他循环内部的循环,形成一个内部循环和一个带有迭代器部分的外部循环。 这些工具在处理矩阵等多维数据结构或需要对每个元素组合执行特定操作时非常有用。

下面是一个嵌套 for 循环的示例,在 C# 中,内循环位于外循环的内部:

    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 2; j++)
        {
            Console.WriteLine($"i: {i}, j: {j}");
        }
    }
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 2; j++)
        {
            Console.WriteLine($"i: {i}, j: {j}");
        }
    }
For i As Integer = 0 To 2
		For j As Integer = 0 To 1
			Console.WriteLine($"i: {i}, j: {j}")
		Next j
Next i
$vbLabelText   $csharpLabel

在这个例子中,外层循环执行并从i等于0开始。内层循环然后遍历j的所有可能值,然后再移动到i的下一个值。

无限循环和循环控制

无限循环是一个永远不会结束的循环,因为其测试条件永远不会变为假。 这些可能是危险的,因为它们可能导致您的程序无限期地挂起。 在编写循环时,如while循环或foreach循环时,要谨慎确保退出条件最终能满足。 以下是 C# 中无指定条件无限循环的示例。

// This is an example of an infinite loop
for (int i = 0; ; i++)
{
    Console.WriteLine("This loop will run forever!");
}
// This is an example of an infinite loop
for (int i = 0; ; i++)
{
    Console.WriteLine("This loop will run forever!");
}
' This is an example of an infinite loop
Dim i As Integer = 0
Do
	Console.WriteLine("This loop will run forever!")
	i += 1
Loop
$vbLabelText   $csharpLabel

除了标准的for循环结构外,C#还提供了循环控制语句,例如breakcontinue,可以帮助您更有效地管理循环。

  • break:此语句用于立即退出循环。当遇到break语句时,循环终止,程序继续执行循环外的下一行代码。
  • continue:此语句用于跳过循环体中当前迭代的剩余代码,并跳到循环的下一次迭代。

    以下是一个在 for 循环中演示使用breakcontinue的示例:

for (int i = 0; i < 10; i++)
{
    if (i == 5)
    {
        break; // Exits the loop when i is equal to 5
    }

    if (i % 2 == 0)
    {
        continue; // Skips even numbers
    }

    Console.WriteLine($"Odd number: {i}");
}
for (int i = 0; i < 10; i++)
{
    if (i == 5)
    {
        break; // Exits the loop when i is equal to 5
    }

    if (i % 2 == 0)
    {
        continue; // Skips even numbers
    }

    Console.WriteLine($"Odd number: {i}");
}
For i As Integer = 0 To 9
	If i = 5 Then
		Exit For ' Exits the loop when i is equal to 5
	End If

	If i Mod 2 = 0 Then
		Continue For ' Skips even numbers
	End If

	Console.WriteLine($"Odd number: {i}")
Next i
$vbLabelText   $csharpLabel

在此示例中,当i达到5时,循环停止执行。 continue语句用于跳过偶数,因此只会打印小于5的奇数。

布尔表达式和循环条件

循环条件是一个布尔值,决定循环是否应继续执行。 此表达式在每次迭代之前计算,只有当表达式为true时,循环才会运行。 许多循环中常用的布尔表达式包括

  • 比较:i < 10i >= 10i >= 10i == 10i != 10
  • 逻辑运算符:&&(与),**

    ** (或),**!`** (非)

    您可以使用逻辑运算符组合多个表达式,创建更复杂的循环条件。 例如

    for (int i = 0; i < 10 && i != 5; i++)
    {
        Console.WriteLine(i);
    }
    for (int i = 0; i < 10 && i != 5; i++)
    {
        Console.WriteLine(i);
    }
Dim i As Integer = 0
Do While i < 10 AndAlso i <> 5
		Console.WriteLine(i)
	i += 1
Loop
$vbLabelText   $csharpLabel

在此示例中,只要i小于10且不等于5,循环将执行。

代码块和循环体

代码块是用大括号{}括起来的一组语句。 在 for 循环中,循环声明之后的代码块称为循环体。 这是您在循环的每次迭代中要执行的代码的位置。

    for (int i = 0; i < 5; i++)
    {
        // This is the loop body
        Console.WriteLine($"Iteration: {i}");
    }
    for (int i = 0; i < 5; i++)
    {
        // This is the loop body
        Console.WriteLine($"Iteration: {i}");
    }
For i As Integer = 0 To 4
		' This is the loop body
		Console.WriteLine($"Iteration: {i}")
Next i
$vbLabelText   $csharpLabel

在这个例子中,循环体包含一个单独的Console.WriteLine语句,该语句打印当前的迭代次数。

循环执行步骤

当您的代码中出现 for 循环时,会发生以下一系列事件:

  1. 循环变量已初始化。

  2. 对布尔表达式进行评估。 如果表达式为false,循环将被跳过,程序继续执行循环外的下一行代码。

  3. 如果表达式为true,则执行循环体。

  4. 循环变量递增或更新。

  5. 步骤2-4重复,直到布尔表达式变为false

集成 IronPdf,使用 For 循环生成报告

了解 IronPDF 的 PDF 生成功能 以用 C# 创建动态且强大的 PDF 报告。 在使用 for 循环时,特别是需要根据循环中处理的数据创建动态报告或文档时,它可能是一个非常有用的工具。 在本节中,我们将向您展示如何结合 C# for 循环使用 IronPDF 生成一份简单的报告。

首先,您需要安装 IronPDF NuGet 软件包。 您可以使用 Visual Studio 中的软件包管理器控制台进行翻译:

    Install-Package IronPDF
    Install-Package IronPDF
SHELL

安装IronPDF后,让我们创建一个简单的示例,生成一个使用IronPDF将HTML转换为PDF的报告,其中包含一个用for循环生成的数字及其平方的表格。

第 1 步:添加必要的命名空间。

    using IronPdf;
    using System.IO;
    using IronPdf;
    using System.IO;
Imports IronPdf
	Imports System.IO
$vbLabelText   $csharpLabel

步骤 2:创建一个名为 GenerateReport 的新方法。

static void GenerateReport()
{
    // Create an HTML template for the report
    var htmlTemplate = @"
    <html>
        <head>
            <style>
                table {
                    border-collapse: collapse;
                    width: 100%;
                }

                th, td {
                    border: 1px solid black;
                    padding: 8px;
                    text-align: center;
                }
            </style>
        </head>
        <body>
            <h1>Number Squares Report</h1>
            <table>
                <thead>
                    <tr>
                        <th>Number</th>
                        <th>Square</th>
                    </tr>
                </thead>
                <tbody>
                    {0}
                </tbody>
            </table>
        </body>
    </html>";

    // Generate the table rows using a for loop
    string tableRows = "";
    for (int i = 1; i <= 10; i++)
    {
        tableRows += $"<tr><td>{i}</td><td>{i * i}</td></tr>";
    }

    // Insert the generated table rows into the HTML template
    string finalHtml = string.Format(htmlTemplate, tableRows);

    // Create a new PDF document from the HTML using two variables
    var pdf = new IronPdf.ChromePdfRenderer();
    var document = pdf.RenderHtmlAsPdf(finalHtml);

    // Save the PDF to a file
    document.SaveAs("NumberSquaresReport.pdf");
}
static void GenerateReport()
{
    // Create an HTML template for the report
    var htmlTemplate = @"
    <html>
        <head>
            <style>
                table {
                    border-collapse: collapse;
                    width: 100%;
                }

                th, td {
                    border: 1px solid black;
                    padding: 8px;
                    text-align: center;
                }
            </style>
        </head>
        <body>
            <h1>Number Squares Report</h1>
            <table>
                <thead>
                    <tr>
                        <th>Number</th>
                        <th>Square</th>
                    </tr>
                </thead>
                <tbody>
                    {0}
                </tbody>
            </table>
        </body>
    </html>";

    // Generate the table rows using a for loop
    string tableRows = "";
    for (int i = 1; i <= 10; i++)
    {
        tableRows += $"<tr><td>{i}</td><td>{i * i}</td></tr>";
    }

    // Insert the generated table rows into the HTML template
    string finalHtml = string.Format(htmlTemplate, tableRows);

    // Create a new PDF document from the HTML using two variables
    var pdf = new IronPdf.ChromePdfRenderer();
    var document = pdf.RenderHtmlAsPdf(finalHtml);

    // Save the PDF to a file
    document.SaveAs("NumberSquaresReport.pdf");
}
Shared Sub GenerateReport()
	' Create an HTML template for the report
	Dim htmlTemplate = "
    <html>
        <head>
            <style>
                table {
                    border-collapse: collapse;
                    width: 100%;
                }

                th, td {
                    border: 1px solid black;
                    padding: 8px;
                    text-align: center;
                }
            </style>
        </head>
        <body>
            <h1>Number Squares Report</h1>
            <table>
                <thead>
                    <tr>
                        <th>Number</th>
                        <th>Square</th>
                    </tr>
                </thead>
                <tbody>
                    {0}
                </tbody>
            </table>
        </body>
    </html>"

	' Generate the table rows using a for loop
	Dim tableRows As String = ""
	For i As Integer = 1 To 10
		tableRows &= $"<tr><td>{i}</td><td>{i * i}</td></tr>"
	Next i

	' Insert the generated table rows into the HTML template
	Dim finalHtml As String = String.Format(htmlTemplate, tableRows)

	' Create a new PDF document from the HTML using two variables
	Dim pdf = New IronPdf.ChromePdfRenderer()
	Dim document = pdf.RenderHtmlAsPdf(finalHtml)

	' Save the PDF to a file
	document.SaveAs("NumberSquaresReport.pdf")
End Sub
$vbLabelText   $csharpLabel

Program.cs文件调用GenerateReport方法:

GenerateReport();
GenerateReport();
GenerateReport()
$vbLabelText   $csharpLabel

来自IronPDF的数字平方报告

运行此示例后,将在应用程序的输出目录中生成名为 "NumberSquaresReport.pdf "的 PDF 报告。 报告将包含一个从 1 到 10 的数字及其平方的表格,使用 C# for 循环生成。

结论

总之,本综合教程为您打下了 C# 循环及其相关概念的坚实基础。我们探讨了循环变量、循环体、迭代变量、内循环和外循环、无限循环、布尔表达式、代码块、嵌套循环,甚至演示了如何集成强大的 IronPDF 库,使用 for 循环生成动态 PDF 报告。

IronPDF 提供IronPDF 的免费试用,让您测试其功能,如果您觉得有帮助,授权费从适合您需求的实惠选项开始。

Chipego
软件工程师
Chipego 拥有出色的倾听技巧,这帮助他理解客户问题并提供智能解决方案。他在 2023 年加入 Iron Software 团队,此前他获得了信息技术学士学位。IronPDF 和 IronOCR 是 Chipego 主要专注的两个产品,但他对所有产品的了解每天都在增长,因为他不断找到支持客户的新方法。他喜欢 Iron Software 的合作氛围,公司各地的团队成员贡献他们丰富的经验,以提供有效的创新解决方案。当 Chipego 离开办公桌时,你经常可以发现他在看书或踢足球。
< 前一页
C# 等待几秒(开发者如何操作)
下一步 >
C#字符串替换(开发人员如何使用)