.NET 幫助

C# for 迴圈(開發人員如何運作)

Chipego
奇佩戈·卡林达
2023年5月16日
分享:

在這個綜合教程中,我們將涵蓋在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++會將i的值增加1。

探索嵌套迴圈

C# 中的巢狀迴圈 是放置在其他迴圈內的迴圈,形成一個內部迴圈和一個具有迭代器部分的外部迴圈。 當您處理像矩陣這樣的多維數據結構時,或者當您需要對每一組元素的組合執行某個操作時,這些功能可能會很有幫助。

以下是一個在 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開始。內層迴圈然後在進入下一個i值之前,遍歷所有可能的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),**

    ** (或), **!`** (非)

    您可以使用邏輯運算符將多個表達式組合起來,以創建更复杂的迴圈條件。 例如:

    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 two variables
    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 two variables
    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 two variables
	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 提供免費試用版,讓您測試其功能,如果您覺得有用,授權選項從適合您需求的價格開始。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
C# 等待秒數(開發人員如何操作)
下一個 >
C# 字符串替換(開發人員如何運作)