跳至页脚内容
.NET 帮助

C# for 循环(开发者如何使用)

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

开始使用for循环

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 Main和循环变量

在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循环的示例:

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 < 10, i >= 10, i > 10, i == 10, i != 10
  • 逻辑运算符:&& (AND),|| (OR),! (NOT)

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

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

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

步骤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 IronPdf
    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 IronPdf
    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 IronPdf
	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#中掌握for循环及其相关概念的坚实基础。我们探索了循环变量、循环体、迭代变量、内部和外部循环、无限循环、布尔表达式、代码块、嵌套循环,甚至演示了如何集成强大的IronPDF库,以便使用for循环生成动态PDF报告。

IronPDF提供IronPDF的免费试用供你测试其功能,如果你觉得有用,许可证从适合你需求的经济选项开始。

常见问题解答

for 循环在 C# 中如何工作?

C# 中的 for 循环用于多次重复执行一段代码。它由三个主要部分组成:初始化、条件和递增,这些控制循环的执行。

'static void Main' 方法在 C# 中的作用是什么?

'static void Main' 方法是 C# 应用程序的入口点。程序从这里开始执行,通常包含初始代码,如 for 循环来执行各种任务。

如何使用 C# 的 for 循环生成 PDF 报告?

您可以使用像 IronPDF 这样的库在 C# 中生成 PDF 报告。for 循环可以用于处理数据并将其格式化为表格或报告,然后可以使用 IronPDF 将其渲染为 PDF 文档。

什么是嵌套循环,它们在 C# 中是如何工作的?

C# 中的嵌套循环是指一个循环内嵌套在另一个循环中。它们对于处理多维数据结构特别有用,因为它们允许对元素组合执行操作。

如何防止 C# 中出现无限循环?

为防止无限循环,确保您的循环条件最终会为 false。使用循环控制语句如 'break' 在满足某个条件时退出循环。

C# 中的 'break' 和 'continue' 语句在循环中是如何使用的?

在 C# 中,'break' 语句用于立即退出循环,而 'continue' 语句跳过当前迭代并继续执行下一次循环迭代。

布尔表达式在 for 循环中如何工作?

for 循环中的布尔表达式决定了循环是否应该继续执行。它们在每次迭代前都会被评估,必须返回 true 才能让循环继续。

如何安装 C# 库以与 for 循环结合使用?

您可以通过 Visual Studio 中的包管理器控制台使用适当的安装命令安装 C# 库,从而在 for 循环中利用其功能。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。