跳過到頁腳內容
.NET幫助

C# For 迴圈(開發者的工作原理)

在本教程中,我們將介紹在 public static void Main 方法中使用 for 迴圈所需的一切。 我們將探討 for 環路、環路變數、環路體、迭代變數、內環路和外環路、無限環路、布林表達式、嵌套環路等。 讓我們開始吧

開始使用 for Loops

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 主變數和循環變數

在 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@ 邏輯運算子: && (與), *|| (OR), !** (不是)

您可以使用邏輯運算符結合多個表達式,以建立更複雜的循環條件。 舉例來說

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,則跳過循環,程式繼續執行循環外的下一行程式碼。

  1. 如果表達式為 true,則執行迴圈體。 4.循環變數遞增或更新。
  2. 重複步驟 2-4,直到布林表達式變為 false

整合 IronPDF,使用 for 迴圈生成報告

了解 IronPDF 的 PDF 生成功能,用 C# 创建動态、健壮的 PDF 报告。 在使用 for 迴圈工作時,特別是需要根據迴圈處理的資料建立動態報表或文件時,它可以成為有用的工具。 在本節中,我們將告訴您如何將 IronPDF 與 C# for 環路結合使用,生成一個簡單的報表。

首先,您需要安裝 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# 迴圈及其相關概念的穩固基礎。我們探討了循環變數、循環體、迭代變數、內環和外環、無限循環、布林表達式、程式碼區塊、巢狀循環,甚至示範了如何整合功能強大的 IronPDF 函式庫,使用 for Loops 來產生動態 PDF 報表。

IronPDF 提供 免費的 IronPDF 試用版,讓您測試其功能,如果您覺得有用,授權起點可從適合您需求的經濟型選項開始。

常見問題解答

C# 中的 for 迴圈如何運作?

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 迴圈中利用其功能。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我