.NET 帮助

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

发布 2023年五月16日
分享:

在本综合教程中,我们将介绍在 "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
VB   C#

让我们来分解 for 循环的各个组成部分:

  1. 初始化:在此声明并初始化循环变量或迭代变量。

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

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

静态 Void 主变量和循环变量

在 C# 中,"static void Main "方法或 "static void Main(字符串 []参数)是应用程序的入口点。程序就是从这里开始执行的。下面是一个循环示例,说明如何在 static void Main 方法中使用 for 循环:


    using System;

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

    using System;

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

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

在本例中,循环变量 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
VB   C#

在此示例中,外循环执行并从 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
VB   C#

除了标准的循环结构外,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
VB   C#

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

布尔表达式和循环条件

循环条件是一个布尔值,决定循环是否应继续执行。每次迭代前都要对该表达式进行评估,只有当表达式为 "true "时,循环才会运行。许多循环中常用的布尔表达式包括

  • 比较: i < 10, i 10, i >= 10, i == 10, i != 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
VB   C#

在本例中,只要 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
VB   C#

在本例中,循环体由一条 Console.WriteLine 语句组成,用于打印当前迭代次数。

循环执行步骤

当代码中出现 for 循环时,会发生以下事件:

1.循环变量已初始化。

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

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

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

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

整合 IronPDF,利用 For 循环生成报告

IronPDF 是一个功能强大的库,用于在 C# 中生成、编辑和渲染 PDF。在使用 for 循环时,尤其是当您需要根据循环中处理的数据创建动态报告或文档时,IronPDF 是一个非常有用的工具。在本节中,我们将向您展示如何将 IronPDF 与 C# for 循环结合使用,以生成一份简单的报告。

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

    Install-Package IronPDF

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

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


    using IronPdf;
    using System.IO;

    using IronPdf;
    using System.IO;
Imports IronPdf
	Imports System.IO
VB   C#

第 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
VB   C#

调用 Program.cs 文件中的 GenerateReport 方法:

GenerateReport();
GenerateReport();
GenerateReport()
VB   C#

数字平方报告

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

结论

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

IronPDF 提供了 免费试用 供您测试其功能,如果您觉得它有用,则可从 $749 开始获得许可。

< 前一页
C# 等待几秒(开发者如何操作)
下一步 >
C#字符串替换(开发人员如何使用)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >