.NET 幫助

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

發佈 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
VB   C#

讓我們分解一個for迴圈的組成部分:

  1. 初始化: 這是在此宣告並初始化迴圈變數或迭代變數的地方。

  2. 條件: 一個布林/條件表達式,它決定迴圈是否應該繼續多次執行語句。

  3. 遞增: 這個語句在每次迭代後更新迭代變數。

靜態無返回值的主方法和循環變數

在C#中,static void Main 方法或 static void Main(字串 []參數)是您的應用程式的入口點。這裡是您的程式開始執行的地方。以下是一個在static void Main` 方法中使用 for 迴圈的範例:


    using System;

    class Program
    {
        static void Main()
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("This is first for loop!");
            }
        }
    }

    using System;

    class Program
    {
        static void Main()
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("This is first for loop!");
            }
        }
    }
Imports System

	Friend Class Program
		Shared Sub Main()
			For i As Integer = 0 To 4
				Console.WriteLine("This is first for loop!")
			Next i
		End Sub
	End Class
VB   C#

在這個例子中,迴圈變量 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
VB   C#

在這個範例中,外層迴圈執行並以 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
VB   C#

除了標準的 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
VB   C#

在這個例子中,當 i 到達 5 時,迴圈停止執行。continue 語句用於跳過偶數,因此只會列印出小於 5 的奇數。

布林表示式和迴圈條件

迴圈條件是一個布林值,決定迴圈是否應該繼續執行。這個表示式在每次迭代之前都會被評估,只有當表示式為 true 時,迴圈才會運行。許多迴圈中常用的布林表示式包括:

  • 比較: i < 10i > 10i >= 10i == 10i ... != 10`**
  • 邏輯運算符: && (和), **`

** (或), ** !``` ** (不)

您可以使用邏輯運算符號結合多個表達式,來創建更複雜的迴圈條件。例如:


    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
VB   C#

在此範例中,迴圈將在 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
VB   C#

在此範例中,迴圈主體包含一個單一的 Console.WriteLine 語句,用於打印當前的迭代次數。

迴圈執行步驟

當程式碼中遇到 for 迴圈時,會發生以下一系列事件:

  1. 初始化迴圈變數。
  2. 評估布林表達式。如果表達式為 false,則跳過迴圈,並且程式繼續執行迴圈外的下一行代碼。
  3. 如果表達式為 true,則執行迴圈體。
  4. 增加或更新迴圈變數。
  5. 重複步驟2-4,直到布林表達式變為 false

使用 IronPDF 產生報告與 For 迴圈集成

IronPDF 是一個強大的金庫,用於在 C#生成、編輯和渲染 PDF。 當處理 for 迴圈時,它可以是一個有用的工具,尤其是當您需要根據迴圈中處理的數據創建動態報告或文檔時。在本部分中,我們將向您展示如何將 IronPDF 與 C# 的 for 迴圈結合使用來生成簡單的報告。

首先,您需要安裝 IronPDF NuGet 套件。您可以使用 Visual Studio 中的包管理器控制台來完成此操作:

    Install-Package IronPDF

安裝好IronPDF後,讓我們創建一個簡單的範例來生成一個 從 HTML 生成的 PDF 報告 包含一個使用 for 迴圈的數字及其平方的表格。

步驟1:添加必要的命名空間。


    using IronPdf;
    using System.IO;

    using IronPdf;
    using System.IO;
Imports IronPdf
	Imports System.IO
VB   C#

第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
VB   C#

從你的Program.cs文件中調用 GenerateReport 方法:

GenerateReport();
GenerateReport();
GenerateReport()
VB   C#

數字方塊報告

當你運行此範例時,名為“NumberSquaresReport.pdf”的 PDF 報告將在您的應用程序輸出目錄中生成。報告將包含一個從 1 到 10 的數字及其平方的表格,這些數字是使用 C# 的 for 迴圈生成的。

結論

總之,這個完整的教程為您提供了 C# 的 for 迴圈及其相關概念的堅實基礎。我們探討了迴圈變量、迴圈體、迭代變量、內部和外部迴圈、無限迴圈、布林表達式、代碼塊、嵌套迴圈,甚至示範了如何使用 for 迴圈整合強大的 IronPDF 庫來生成動態 PDF 報告。

IronPDF 提供了一個 免費試用 讓您測試其功能,如果您覺得有用,授權費用從 $749 開始。

< 上一頁
C# 等待秒數(開發人員如何操作)
下一個 >
C# 字符串替換(開發人員如何運作)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >