.NET 幫助

C#繼續(對開發人員的工作方式)

介紹

流程控制語句在程式設計中至關重要,因為它們決定了程式中指令的執行順序。 在 C# 中,用於控制迴圈的三個基本語句是「continue」、「break」和「goto」。 這些語句為程式設計師提供了改變迴圈內執行流程的能力,提高了程式碼的效率和可讀性。 在本文中,我們深入探討 C# 中 continuebreak 方法的複雜性,探索它們的語法、應用和最佳實踐。 稍後在本文中,我們還將了解IronPDF - 一個強大的 C# PDF 函式庫來自Iron Software,用於讀取和寫入 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 skip 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 skip 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 skip 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(開發人員運作方式):圖 1 - 控制台輸出顯示由於 continue 語句而跳過案例 5

探索 '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;' 語句

goto 語句在 C# 中提供了一種在相同方法、相同 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 標籤,從而有效地跳出嵌套迴圈。

介紹IronPDF - 全方位 PDF 庫,來自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,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。

    • 作業系統和處理器:可在 Windows、Mac 和 Linux (x64, x86, ARM) 上運行。
  5. PDF 標準和編輯

    • 支持各種 PDF 版本 (1.2 - 1.7)、PDF/UA 和 PDF/A。

    • 為 PDF 文件設置屬性、安全性和壓縮。

    • 編輯元數據、修訂歷史和文件結構。

    • 套用頁面模板、頁首、頁尾和頁面設定。
  6. 性能優化

    • 全多執行緒和異步支持以高效生成 PDF。

    • 優先考慮準確性、易用性和速度。

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

使用繼續語句生成 PDF 文件

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

C# Continue(開發者如何使用它):圖2 - 創建 Visual Studio 主控台應用程式

提供專案名稱和位置。

C# Continue(它如何對開發者起作用):圖3 - 提供專案名稱

下一步,選擇所需的 .NET 版本並點擊創建。

現在使用以下命令安裝IronPDF。

dotnet add package IronPdf --version 2024.4.2
dotnet add package IronPdf --version 2024.4.2
SHELL

現在讓我們使用控制語句生成一個PDF文檔。

using System;
using System.Threading.Tasks;
using System.Diagnostics;
using IronPdf;
class Program
{
    public static async Task Main()
    {
        Console.WriteLine("Generate PDF document Using IronPDF");
        var htmlToPdf = new ChromePdfRenderer();
        var content = "<h1>Generate Numbers from 1 to 10, skip 5</h1>";
        for (int i = 0; i < 10; i++)
        {
            if (i == 5)
            {
                continue;
            }
            content += $"<p>{i}</p>";
        }
        content += "<h1>Generate Numbers from 1 to 10, stop at 7</h1>";
        for (int i = 0; i < 10; i++)
        {
            if (i == 7)
            {
                break;
            }
            content += $"<p>{i}</p>";
        }
        var pdf = htmlToPdf.RenderHtmlAsPdf(content);
        pdf.SaveAs("AwesomeIronPDF.pdf");
        Console.WriteLine("PDF generated successfully.");
    }
}
using System;
using System.Threading.Tasks;
using System.Diagnostics;
using IronPdf;
class Program
{
    public static async Task Main()
    {
        Console.WriteLine("Generate PDF document Using IronPDF");
        var htmlToPdf = new ChromePdfRenderer();
        var content = "<h1>Generate Numbers from 1 to 10, skip 5</h1>";
        for (int i = 0; i < 10; i++)
        {
            if (i == 5)
            {
                continue;
            }
            content += $"<p>{i}</p>";
        }
        content += "<h1>Generate Numbers from 1 to 10, stop at 7</h1>";
        for (int i = 0; i < 10; i++)
        {
            if (i == 7)
            {
                break;
            }
            content += $"<p>{i}</p>";
        }
        var pdf = htmlToPdf.RenderHtmlAsPdf(content);
        pdf.SaveAs("AwesomeIronPDF.pdf");
        Console.WriteLine("PDF generated successfully.");
    }
}
Imports System
Imports System.Threading.Tasks
Imports System.Diagnostics
Imports IronPdf
Friend Class Program
	Public Shared Async Function Main() As Task
		Console.WriteLine("Generate PDF document Using IronPDF")
		Dim htmlToPdf = New ChromePdfRenderer()
		Dim content = "<h1>Generate Numbers from 1 to 10, skip 5</h1>"
		For i As Integer = 0 To 9
			If i = 5 Then
				Continue For
			End If
			content &= $"<p>{i}</p>"
		Next i
		content &= "<h1>Generate Numbers from 1 to 10, stop at 7</h1>"
		For i As Integer = 0 To 9
			If i = 7 Then
				Exit For
			End If
			content &= $"<p>{i}</p>"
		Next i
		Dim pdf = htmlToPdf.RenderHtmlAsPdf(content)
		pdf.SaveAs("AwesomeIronPDF.pdf")
		Console.WriteLine("PDF generated successfully.")
	End Function
End Class
$vbLabelText   $csharpLabel

程式碼說明

  1. 最初,我們正在創建用於 PDF 文件的內容。

  2. 我們將內容準備為 HTML 文檔。

  3. 我們在 for 迴圈內使用 continue 語句來列印從 1 到 10,並跳過 5。

  4. 此外,我們使用break語句從 1 印到 7 然後中斷。

  5. 然後,我們使用 ChromePdfRenderer 物件將 HTML 文件儲存為 PDF 文件。

輸出

C# 繼續(開發人員如何使用):圖 4 - 範例輸出展示了 continue 和 break 方法的運作方式

最佳實踐和考慮事項

  1. 清晰度和可讀性:在大多數情況下,使用像breakcontinue或嵌套迴圈這樣的結構化控制流語句,可以提高程式碼的可讀性和易懂性。 goto 語句可能會使代碼變得難以理解,特別是在大型代碼庫或過度使用時。

  2. 避免意外後果:誤用goto可能導致意大利麵條式代碼,使得難以推理程式行為。 至關重要的是謹慎使用goto,並確保其使用方式清晰且有良好的文件記錄。

  3. 錯誤處理goto的常見用例之一是在錯誤處理場景中,使用它可以跳至清理或錯誤處理例程。然而,現代的 C# 代碼庫通常使用結構化的例外處理(try-catch-finally)來進行錯誤處理,這提供了一種更具結構性和可讀性的方法。

  4. 性能考量:就性能而言,goto 通常影響不大。 然而,主要關注的問題是的可維護性和可讀性,而非性能。

許可證(提供試用)

查看 IronPDF 授權詳細資訊

開發者試用授權可用,獲取試用授權

請替換應用程式設定檔 appSettings.json 中的 Key。

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

結論

總結來說,continuebreak 方法是控制 C# 中迴圈執行不可或缺的工具。 通過將這些語句策略性地整合到您的代碼中,您可以提高其效率、可讀性和可維護性。 雖然 C# 中的goto語句提供了一種改變執行流的機制,但應謹慎使用。 在大多數情況下,結構化的控制流程語句如breakcontinue或巢狀迴圈提供更清晰且更易維護的解決方案。 然而,在某些利基情境中,goto 可以被有效且安全地使用,例如在某些錯誤處理情況中。 與任何程式設計結構一樣,在決定是否使用 goto 時,權衡取捨並考慮程式碼的可讀性和可維護性是至關重要的。

結合IronPDF - Comprehensive PDF Solutions庫與Iron Software,以讀取和生成 PDF 文件,開發者可以獲得先進的技能來開發現代應用程式。

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