跳過到頁腳內容
.NET幫助

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
$vbLabelText   $csharpLabel

讓我們分解for循環的組成部分:

  1. 初始化:這是宣告並初始化循環變量或迭代變量的地方。
  2. 條件:布林或條件表達式,用於確定循環是否應多次執行語句。
  3. 遞增:此語句在每次迭代後更新迭代變量。

靜態空白主程序和循環變量

在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++的值增加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值。

無限循環和循環控制

無限循環是由於其測試條件永遠不會變為假而從未終止的循環。 這些可能很危險,因為它們可能導致程序無限掛起。 在編寫循環時需謹慎,如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 < 10i >= 10i > 10i == 10i != 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
$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,則跳過循環,程序繼續執行循環外的下一行代碼。
  3. 如果表達式為true,則執行循環體。
  4. 循環變數被遞增或更新。
  5. 重複步驟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
$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# for循環及其相關概念的堅實基礎。我們已經探討了循環變量、循環主體、迭代變量、內外循環、無限循環、布林表達式、代碼塊、嵌套循環,甚至還展示了如何整合功能強大的IronPDF庫使用for循環來生成動態的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 迴圈中利用其功能。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。