跳過到頁腳內容
.NET幫助

C# Continue(對於開發者的運行原理)

控制流程語句在程式設計中至關重要,因為它們決定了程式中指令的執行順序。 在 C# 中,控制循環的三個基本語句是"continue"、"break"和"goto"。 這些語句提供程式設計師改變循環內執行流程的能力,提升程式碼的效率與可讀性。 在這篇文章中,我們會深入探討 C# 中 continuebreak 方法的複雜性,探索它們的語法、應用和最佳實作。 在文章的後面,我們還將了解 IronPDF - 來自 Iron Software 的強大 C# PDF 函式庫,用來讀取和寫入 PDF 文件。

瞭解 'continue;'語句。

continue 語句用於循環結構中,以跳過餘下的程式碼區塊,並進入循環的下一次迭代。它基本上是告訴程式控制跳過目前迭代的剩餘程式碼,並進入下一個迭代。

文法

continue;
continue;
continue
$vbLabelText   $csharpLabel

範例

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Demonstrate Continue Method in C#");
        Console.WriteLine("Print 1 to 10 skipping 5");

        for (int i = 0; i < 10; i++)
        {
            if (i == 5)
            {
                continue; // Skips iteration when i equals 5
            }
            Console.WriteLine(i);
        }
    }
}
public class Program
{
    public static void Main()
    {
        Console.WriteLine("Demonstrate Continue Method in C#");
        Console.WriteLine("Print 1 to 10 skipping 5");

        for (int i = 0; i < 10; i++)
        {
            if (i == 5)
            {
                continue; // Skips iteration when i equals 5
            }
            Console.WriteLine(i);
        }
    }
}
Public Class Program
	Public Shared Sub Main()
		Console.WriteLine("Demonstrate Continue Method in C#")
		Console.WriteLine("Print 1 to 10 skipping 5")

		For i As Integer = 0 To 9
			If i = 5 Then
				Continue For ' Skips iteration when i equals 5
			End If
			Console.WriteLine(i)
		Next i
	End Sub
End Class
$vbLabelText   $csharpLabel

在這個範例中,當 i 等於 5 時,會執行 continue 語句,跳過該迭代循環中餘下的程式碼。 結果,數字 5 將不會被列印,而循環會繼續到下一個迭代。

輸出

C# Continue (How It Works For Developers):圖 1 - 控制台輸出顯示 case 5 因為 continue 語句而被跳過

探索"break; "方法

continue相反,break語句用於過早退出循環。 當遇到時,它會終止循環的執行,不論循環的條件為何。 通常用來退出迴圈,例如 while 迴圈,如果滿足特定條件就提前退出。

範例

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
foreach (int number in numbers)
{
    if (number == 6)
    {
        break; // Exits loop when number equals 6
    }
    Console.WriteLine(number);
}
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
foreach (int number in numbers)
{
    if (number == 6)
    {
        break; // Exits loop when number equals 6
    }
    Console.WriteLine(number);
}
Dim numbers() As Integer = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
For Each number As Integer In numbers
	If number = 6 Then
		Exit For ' Exits loop when number equals 6
	End If
	Console.WriteLine(number)
Next number
$vbLabelText   $csharpLabel

在這個範例中,循環遍歷 numbers 陣列。 當遇到數字 6 時,會執行 break 語句,導致循環提前終止。 因此,只會印出數字 1 到 5。

探索 'goto;' 語句

C# 中的 goto 語句提供了一種方法,可在相同的方法、相同的 switch 語句或相同的循環中,將控制權轉移到指定的標籤。雖然 goto 可以是改變執行流程跳轉語句的強大工具,但由於它可能會使程式碼的可讀性和可維護性降低,因此在現代程式設計實務中通常不鼓勵使用。 然而,在某些情況下,goto 可以有效且安全地使用。

文法

C# 中 goto 語句的語法簡單直接:

goto label;
goto label;
GoTo label
$vbLabelText   $csharpLabel

其中,標籤是一個識別符號,後面跟一個冒號 (:),表示在程式碼中的目標位置。

範例

考慮一種情況:當滿足特定條件時,您想要提前退出巢狀循環。 您可以使用 goto 語句來達成這個目標:

for (int i = 0; i < 5; i++)
{
    for (int j = 0; j < 5; j++)
    {
        if (i * j > 10)
        {
            goto exitLoop;
        }
        Console.WriteLine($"i: {i}, j: {j}");
    }
}
exitLoop:
Console.WriteLine("Exited the nested loop prematurely.");
for (int i = 0; i < 5; i++)
{
    for (int j = 0; j < 5; j++)
    {
        if (i * j > 10)
        {
            goto exitLoop;
        }
        Console.WriteLine($"i: {i}, j: {j}");
    }
}
exitLoop:
Console.WriteLine("Exited the nested loop prematurely.");
For i As Integer = 0 To 4
	For j As Integer = 0 To 4
		If i * j > 10 Then
			GoTo exitLoop
		End If
		Console.WriteLine($"i: {i}, j: {j}")
	Next j
Next i
exitLoop:
Console.WriteLine("Exited the nested loop prematurely.")
$vbLabelText   $csharpLabel

在這個範例中,當條件 i * j > 10 符合時,goto 語句會將控制轉移到 exitLoop 標籤,有效地跳出嵌套循環。

Introducing IronPDF - Comprehensive PDF Library from Iron Software..

IronPDF由 Iron Software 開發,是功能強大的 C# PDF 函式庫,提供在 .NET 專案中處理 PDF 的多合一解決方案。 無論您需要建立、編輯、匯出、保全、載入或處理 PDF 文件,IronPDF 都能滿足您的需求。 以下是一些主要功能和使用案例:

1.HTML 至 PDF 轉換:將 HTML 內容無縫轉換為 PDF 格式。 您可以從 HTML、MVC、ASPX 甚至圖片產生 PDF。 2.簽署、編輯和閱讀 PDF:IronPDF 擁有超過 50 項功能,可讓您簽署、編輯 PDF 檔案,並從 PDF 檔案中擷取內容。 無論您是要新增數位簽章或修改現有的 PDF,IronPDF 都能讓您一目了然。 3.跨平台支援:IronPDF 專為 C#、F# 和 VB.NET 所設計,可在各種 .NET 版本上執行,包括 .NET Core、.NET Standard 和 .NET Framework。 它也適用於 Java、Node.js 和 Python。 4.相容性與環境

  • .NET 版本:支援 C#、VB.NET 和 F#。
  • 專案類型:適用於網頁 (Blazor & WebForms)、桌上型電腦 (WPF & MAUI) 以及主控台應用程式。
  • 應用環境:相容於 Windows、Linux、Mac、Docker、Azure、AWS 等。
  • IDEs: 可與 Microsoft Visual Studio 和 JetBrains Rider 無縫整合。
  • OS 與處理器:可在 Windows、Mac 和 Linux (x64, x86, ARM) 上執行。 5.PDF 標準與編輯
  • 支援各種 PDF 版本 (1.2 - 1.7)、PDF/UA 及 PDF/A。
  • 設定 PDF 檔案的屬性、安全性和壓縮。
  • 編輯元資料、修訂歷史和文件結構。
  • 套用頁面範本、頁首、頁尾及頁面設定。 6.效能最佳化
  • 完整的多執行緒與 async 支援,可有效率地產生 PDF。
  • 優先考量準確性、易用性和速度。

既然我們已瞭解 IronPDF 函式庫,讓我們來撰寫一個應用程式,以使用 IronPDF 和 continue 語句、break 語句以及 goto 語句。

使用 Continue Statement 生成 PDF 文件。

首先,讓我們建立一個 Visual Studio 主控台應用程式。

C# Continue (How It Works For Developers):圖 2 - 建立 Visual Studio 控制台應用程式

提供專案名稱和地點。

C# Continue (How It Works For Developers):圖 3 - 提供專案名稱

下一步,選擇所需的 .NET 版本,然後按一下建立。

現在使用以下指令安裝 IronPdf。

dotnet add package IronPdf --version 2024.4.2

現在讓我們使用控制語句產生 PDF 文件。

using System;
using System.Threading.Tasks;
using IronPdf;

class Program
{
    public static async Task Main()
    {
        Console.WriteLine("Generate PDF document Using IronPDF");

        // Initialize a ChromePdfRenderer to render HTML content to PDF
        var htmlToPdf = new ChromePdfRenderer();
        var content = "<h1>Generate Numbers from 1 to 10, skip 5</h1>";

        // Use continue statement to build HTML content
        for (int i = 0; i < 10; i++)
        {
            if (i == 5)
            {
                continue; // Skip appending number 5 to the content
            }
            content += $"<p>{i}</p>";
        }

        content += "<h1>Generate Numbers from 1 to 10, stop at 7</h1>";

        // Use break statement to terminate loop at 7
        for (int i = 0; i < 10; i++)
        {
            if (i == 7)
            {
                break; // Stop appending numbers after 6
            }
            content += $"<p>{i}</p>";
        }

        // Render the HTML content as a PDF document
        var pdf = await htmlToPdf.RenderHtmlAsPdfAsync(content);
        pdf.SaveAs("AwesomeIronPDF.pdf");

        Console.WriteLine("PDF generated successfully.");
    }
}
using System;
using System.Threading.Tasks;
using IronPdf;

class Program
{
    public static async Task Main()
    {
        Console.WriteLine("Generate PDF document Using IronPDF");

        // Initialize a ChromePdfRenderer to render HTML content to PDF
        var htmlToPdf = new ChromePdfRenderer();
        var content = "<h1>Generate Numbers from 1 to 10, skip 5</h1>";

        // Use continue statement to build HTML content
        for (int i = 0; i < 10; i++)
        {
            if (i == 5)
            {
                continue; // Skip appending number 5 to the content
            }
            content += $"<p>{i}</p>";
        }

        content += "<h1>Generate Numbers from 1 to 10, stop at 7</h1>";

        // Use break statement to terminate loop at 7
        for (int i = 0; i < 10; i++)
        {
            if (i == 7)
            {
                break; // Stop appending numbers after 6
            }
            content += $"<p>{i}</p>";
        }

        // Render the HTML content as a PDF document
        var pdf = await htmlToPdf.RenderHtmlAsPdfAsync(content);
        pdf.SaveAs("AwesomeIronPDF.pdf");

        Console.WriteLine("PDF generated successfully.");
    }
}
Imports System
Imports System.Threading.Tasks
Imports IronPdf

Friend Class Program
	Public Shared Async Function Main() As Task
		Console.WriteLine("Generate PDF document Using IronPDF")

		' Initialize a ChromePdfRenderer to render HTML content to PDF
		Dim htmlToPdf = New ChromePdfRenderer()
		Dim content = "<h1>Generate Numbers from 1 to 10, skip 5</h1>"

		' Use continue statement to build HTML content
		For i As Integer = 0 To 9
			If i = 5 Then
				Continue For ' Skip appending number 5 to the content
			End If
			content &= $"<p>{i}</p>"
		Next i

		content &= "<h1>Generate Numbers from 1 to 10, stop at 7</h1>"

		' Use break statement to terminate loop at 7
		For i As Integer = 0 To 9
			If i = 7 Then
				Exit For ' Stop appending numbers after 6
			End If
			content &= $"<p>{i}</p>"
		Next i

		' Render the HTML content as a PDF document
		Dim pdf = Await htmlToPdf.RenderHtmlAsPdfAsync(content)
		pdf.SaveAs("AwesomeIronPDF.pdf")

		Console.WriteLine("PDF generated successfully.")
	End Function
End Class
$vbLabelText   $csharpLabel

程式碼解釋

1.初始化並定義內容:我們先定義要包含在 PDF 中的 HTML 內容。 2.使用 continue: 在第一個循環中,我們使用 continue 語句在產生 1 到 10 的數字時跳過數字 5。 3.使用 break: 在第二個循環中,我們使用 break 語句在數字 7 到達時停止循環。 4.渲染 PDF:我們使用 ChromePdfRenderer 物件將 HTML 內容轉換為 PDF 檔案並儲存。

輸出

C# Continue (How It Works For Developers):圖 4 - 展示 continue 和 break 方法如何運作的輸出範例

最佳實務與注意事項

1.清晰度和可讀性:在大多數情況下,使用結構化的控制流程語句,例如 breakcontinue 或嵌套循環,可以讓您的程式碼更具可讀性和易懂性。 goto 語句會使程式碼更難遵循,尤其是對於較大的程式碼庫或過度使用時。 2.避免意想不到的後果:誤用 goto可能會導致程式碼變得亂七八糟,難以推理程式行為。 必須謹慎使用 goto,並確保其用法明確且文件齊全。 3.錯誤處理goto 的一個常見用例是在錯誤處理的情況下,它可以用來跳到清理或錯誤處理例程。然而,現代的 C# 程式碼常使用結構化的異常處理 (try-catch-finally) 來處理錯誤,這提供了更有條理和可讀性的方法。 4.效能考量:就效能而言,goto 通常影響極小。 不過,goto的主要考量是可維護性和可讀性,而非效能。

授權(可試用)

探索 IronPDF 授權詳情

提供開發人員試用授權 取得試用授權

請取代下圖 appSettings.json 檔案中的 Key。

{
  "IronPdf.License.LicenseKey": "The Key Here"
}

結論

總而言之,continuebreak 方法是 C# 中控制循環執行不可或缺的工具。 透過策略性地將這些陳述融入您的程式碼中,您可以提升程式碼的效率、可讀性和可維護性。 雖然 C# 中的 goto 語句提供了改變執行流程的機制,但仍需謹慎使用。 在大多數情況下,結構化的控制流程語句,例如 breakcontinue 或巢狀迴圈,都能提供更清晰、更易維護的解決方案。 然而,在一些小眾的情況下,也可以有效且安全地使用 goto,例如在某些錯誤處理的情況下。 就像任何程式結構一樣,在決定是否使用 goto 時,權衡利弊並考慮程式碼的可讀性和可維護性是非常重要的。

連同 Iron SoftwareIronPDF - Comprehensive PDF Solutions 函式庫,開發人員可以獲得開發現代應用程式的進階技能。

常見問題解答

在 C# 中,「continue」語句如何運作?

C# 中的「continue」語句用於迴圈中,跳過目前迭代中的剩餘程式碼,直接進入下一個迭代。這對於繞過某些條件或值非常有用,例如跳過循環中的數字 5。

break "語句在循環中的作用是什麼?

break "語句用於在滿足特定條件時提前退出循環。這有助於在某一點停止循環,例如在達到數字 6 之後停止迭代。

在 C# 中,何時應該使用「goto」語句?

雖然「goto」語句允許您跳轉到代碼中標示的部分,但由於潛在的可讀性問題,一般不鼓勵使用。它最好用在其他控制結構效率較低或較不清楚的特定場合。

如何將 IronPDF 整合到 C# 專案中?

使用命令 dotnet add package IronPdf --version [version_number] 可以將 IronPDF 整合到 C# 專案中,從而在各種 .NET 環境中創建、編輯和轉換 PDF。

在 C# 中使用全面的 PDF 函式庫有哪些優點?

像 IronPDF 這種全面的 PDF 函式庫能提供強大的 PDF 建立、編輯和轉換功能,從而增強 C# 應用程式。它支援 HTML 至 PDF 的轉換,並提供跨平台支援,使其成為開發人員的多用途工具。

控制流程語句如何改善 C# 中 PDF 的產生?

在 PDF 生成过程中,"continue 「和 」break "等控制流语句可用于管理循环的执行,允许开发人员在使用 IronPDF 时根据特定条件有选择地添加内容或停止内容生成。

IronPdf 有哪些相容性功能?

IronPDF 兼容各種 .NET 版本,包括 .NET Core、.NET Standard 和 .NET Framework。它支援 C#、VB.NET 和 F# 等多種語言,並與 Microsoft Visual Studio 和 JetBrains Rider 等 IDE 整合。

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

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

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

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。