跳過到頁腳內容
.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
}
$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!");
        }
    }
}
$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}");
    }
}
$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!");
}
$vbLabelText   $csharpLabel

除了標準的 for 迴圈結構外,C# 還提供了迴圈控制語句,例如 breakcontinue,可以幫助您更有效地管理迴圈。

  • break語句時,循環終止,程式繼續執行循環外的下一行程式碼。
  • continue:此語句用於跳過目前迭代循環體中的剩餘程式碼,並跳到循環的下一個迭代。

以下範例示範如何在 for 迴圈中使用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}");
}
$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);
}
$vbLabelText   $csharpLabel

在這個例子中,只要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}");
}
$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;
$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");
}
$vbLabelText   $csharpLabel

Program.cs檔呼叫 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 迴圈中利用其功能。

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技術的創新,同時指導下一代技術領導者。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me