
C# For 迴圈(開發者的工作原理)
在這個全面的教程中,我們將涵蓋在public static void Main方法中開始使用for迴圈所需了解的一切。 我們將探索for迴圈、迴圈變數、迴圈主體、迭代變數、內迴圈和外迴圈、無限迴圈、布林表達式、巢狀迴圈等。 讓我們開始吧!
開始使用for迴圈
一個for迴圈是在C#中專為您明確知道想要迭代的次數而設計的一種迴圈。 C#中for迴圈的語法如下程式碼塊所示:
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!");
}
}
}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 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
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 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);
}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 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中的套件管理器控制台完成此操作:
一旦安裝了IronPDF,讓我們建立一個簡單的範例,通過IronPDF從HTML生成包含數字和其平方的表格的PDF報告,使用for迴圈。
步驟1:新增必要的命名空間。
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");
}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()
當您執行此範例時,將在您的應用程式輸出目錄中生成一個名為"NumberSquaresReport.pdf"的PDF報告。 報告將包含一個由1到10的數字及其平方組成的表格,這是透過C# for迴圈生成的。
結論
總結來說,這個全面的教程提供了涵蓋C# for迴圈及其相關概念的堅實基礎。我們探索了迴圈變數、迴圈主體、迭代變數、內外迴圈、無限迴圈、布林表達式、程式碼塊、巢狀迴圈,甚至展示了如何整合強大的IronPDF程式庫以使用for迴圈生成動態PDF報告。
IronPDF提供免費試用IronPDF供您測試其功能,如果您覺得有用,許可證將從符合您需求的經濟選擇開始。

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。
相關文章


