在生产环境中测试,无水印。
随时随地满足您的需求。
获得30天的全功能产品。
几分钟内就能启动并运行。
在您的产品试用期间,全面访问我们的支持工程团队。
在本综合教程中,我们将涵盖所有您需要知道的内容,以便在public static void Main
方法中开始使用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
让我们来分析一下 for 循环的组成部分:
初始化:这是声明和初始化循环变量或迭代变量的地方。
条件:一个布尔/条件表达式,用于决定循环是否应继续多次执行语句。
在 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
在此示例中,循环变量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
在这个例子中,外层循环执行并从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
除了标准的for循环结构外,C#还提供了循环控制语句,例如break
和continue
,可以帮助您更有效地管理循环。
break
:此语句用于立即退出循环。当遇到break
语句时,循环终止,程序继续执行循环外的下一行代码。continue
:此语句用于跳过循环体中当前迭代的剩余代码,并跳到循环的下一次迭代。
以下是一个在 for 循环中演示使用break
和continue
的示例:
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
在此示例中,当i
达到5
时,循环停止执行。 continue
语句用于跳过偶数,因此只会打印小于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
在此示例中,只要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
在这个例子中,循环体包含一个单独的Console.WriteLine
语句,该语句打印当前的迭代次数。
当您的代码中出现 for 循环时,会发生以下一系列事件:
循环变量已初始化。
对布尔表达式进行评估。 如果表达式为false
,循环将被跳过,程序继续执行循环外的下一行代码。
如果表达式为true
,则执行循环体。
循环变量递增或更新。
false
。了解 IronPDF 的 PDF 生成功能 以用 C# 创建动态且强大的 PDF 报告。 在使用 for 循环时,特别是需要根据循环中处理的数据创建动态报告或文档时,它可能是一个非常有用的工具。 在本节中,我们将向您展示如何结合 C# for 循环使用 IronPDF 生成一份简单的报告。
首先,您需要安装 IronPDF NuGet 软件包。 您可以使用 Visual Studio 中的软件包管理器控制台进行翻译:
Install-Package IronPDF
Install-Package IronPDF
安装IronPDF后,让我们创建一个简单的示例,生成一个使用IronPDF将HTML转换为PDF的报告,其中包含一个用for循环生成的数字及其平方的表格。
第 1 步:添加必要的命名空间。
using IronPdf;
using System.IO;
using IronPdf;
using System.IO;
Imports IronPdf
Imports System.IO
步骤 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
从Program.cs文件调用GenerateReport
方法:
GenerateReport();
GenerateReport();
GenerateReport()
运行此示例后,将在应用程序的输出目录中生成名为 "NumberSquaresReport.pdf "的 PDF 报告。 报告将包含一个从 1 到 10 的数字及其平方的表格,使用 C# for 循环生成。
总之,本综合教程为您打下了 C# 循环及其相关概念的坚实基础。我们探讨了循环变量、循环体、迭代变量、内循环和外循环、无限循环、布尔表达式、代码块、嵌套循环,甚至演示了如何集成强大的 IronPDF 库,使用 for 循环生成动态 PDF 报告。
IronPDF 提供IronPDF 的免费试用,让您测试其功能,如果您觉得有帮助,授权费从适合您需求的实惠选项开始。