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
讓我們分解for迴圈的組成部分:
- 初始化: 這是聲明和初始化迴圈變數或迭代變數的地方。
- 條件: 確定迴圈是否應繼續多次執行語句的布林/條件表達式。
- 增量: 這個語句在每次迭代後更新迭代變數。
靜態空白主和迴圈變數
在C#中,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,並作為變數運作。 只要5,迴圈將繼續執行。 在每次迭代後,增量操作i的值增加1。
探索巢狀迴圈
巢狀迴圈是放置在其他迴圈內的迴圈,形成內迴圈和帶有迭代器部分的外迴圈。 這些在處理如矩陣之類的多維資料結構或當您需要對每一個元素組合執行某些操作時很有用。
這是一個內迴圈放在外迴圈中的巢狀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值。
無限迴圈和迴圈控制
一個無限迴圈是一個永遠不會結束的迴圈,因為它的測試條件永遠不會成為假。 這些可能很危險,因為它們可能會導致您的程式無限期地掛起。 在編寫如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#還提供了如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
在此範例中,當5時,迴圈將停止執行。 5的奇數。
布林表達式和迴圈條件
迴圈條件是一個決定迴圈是否應繼續執行的布林表達式。 此表達式在每次迭代前被評估,只有當表達式為true時,迴圈才會運行。 許多迴圈中常用的布林表達式包括:
- Comparisons:
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
在此範例中,迴圈將在 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,則執行迴圈主體。 - 迴圈變數被遞增或更新。
- 重複步驟2-4,直到布林表達式變為
false。
整合IronPDF以使用For迴圈生成報告
了解IronPDF的PDF生成功能,以在C#中建立動態且可靠的PDF報告。 這可以是您在使用for迴圈時的一個有用工具,特別是當您需要根據迴圈中處理的資料建立動態報告或文件時。 在此部分,我們將向您展示如何使用IronPDF結合C# for迴圈生成簡單的報告。
首先,您需要安裝IronPDF NuGet套件。 您可以使用Visual Studio中的套件管理器控制台完成此操作:
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 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
從您的Program.cs文件調用GenerateReport方法:
GenerateReport();
GenerateReport();
GenerateReport()

當您執行此範例時,將在您的應用程式輸出目錄中生成一個名為"NumberSquaresReport.pdf"的PDF報告。 報告將包含一個由1到10的數字及其平方組成的表格,這是透過C# for迴圈生成的。
結論
總結來說,這個全面的教程提供了涵蓋C# for迴圈及其相關概念的堅實基礎。我們探索了迴圈變數、迴圈主體、迭代變數、內外迴圈、無限迴圈、布林表達式、程式碼塊、巢狀迴圈,甚至展示了如何整合強大的IronPDF程式庫以使用for迴圈生成動態PDF報告。
IronPDF提供免費試用IronPDF供您測試其功能,如果您覺得有用,許可證將從符合您需求的經濟選擇開始。
常見問題
C# 中的 for 迴圈如何運作?
C# 中的 for 迴圈用於執行一段程式碼多次。它由三個主要部分組成:初始化、條件和遞增,這控制著迴圈的執行。
C# 中的 `static void Main` 方法的作用是什麼?
‘static void Main’ 方法作為 C# 應用程式的入口點。它是程式開始執行的地方,通常包括初始程式碼如 for 迴圈來執行各種任務。
如何使用 C# 中的 for 迴圈生成 PDF 報告?
您可以使用像 IronPDF 這樣的程式庫來在 C# 中生成 PDF 報告。for 迴圈可以用於處理資料並將其格式化為表格或報告,然後可以使用 IronPDF 將其渲染為 PDF 文件。
什麼是巢狀迴圈,它們如何在 C# 中運作?
C# 中的巢狀迴圈是巢狀在其他迴圈中的迴圈。它們特別適用於處理多維資料結構,因為它們允許您對元素的組合進行操作。
如何在 C# 中防止無限迴圈?
為了防止無限迴圈,請確保您的迴圈條件最終會成為假。使用‘break’等迴圈控制語句,在滿足某個條件時退出迴圈。
‘break’ 和 ‘continue’ 語句在 C# 迴圈中用於什麼?
在 C# 中,‘break’ 語句用於立即退出迴圈,而‘continue’ 語句則跳過當前迭代並繼續下一個迴圈的迭代。
布林表達式在 for 迴圈中如何運作?
for 迴圈中的布林表達式確定迴圈是否應該繼續執行。它們在每次迭代之前進行評估,必須返回真才能使迴圈繼續。
如何安裝 C# 程式庫以便與 for 迴圈一起使用?
您可以通過 Visual Studio 中的封裝管理器控制台使用適當的安裝命令安裝 C# 程式庫,讓您在 for 迴圈中利用其功能。




