跳至页脚内容
.NET 帮助

C# Continue(开发人员如何使用)

控制流语句在编程中至关重要,因为它们决定了程序中指令的执行顺序。 在 C# 中,控制循环的三个基本语句是 'continue','break' 和 'goto'。 这些语句为程序员提供了在循环中改变执行流的能力,从而提高代码的效率和可读性。 在本文中,我们深入探讨 continuebreak 方法在 C# 中的细节,探索它们的语法、应用和最佳实践。 Later in the article, we will also learn about IronPDF - a robust C# PDF library from Iron Software to read and write PDF documents.

理解 '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 - 控制台输出显示由于 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;' 语句

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:凭借超过 50 个功能,IronPDF 使您能够签名、编辑和提取 PDF 文件的内容。 无论您是在添加数字签名还是修改现有的 PDFs,IronPDF 使其变得简单易行。
  3. 跨平台支持:IronPDF 针对 C#、F# 和 VB.NET 进行设计,并能在包括 .NET Core、.NET Standard 和 .NET Framework 的各种 .NET 版本上运行。 它还可用于 Java、Node.js 和 Python。
  4. 兼容性和环境
    • .NET 版本:支持 C#、VB.NET 和 F#。
    • 项目类型:适用于网络项目(Blazor 和 WebForms)、桌面(WPF 和 MAUI)和控制台应用程序。
    • 应用环境:兼容 Windows、Linux、Mac、Docker、Azure、AWS 以及更多。
    • IDE:与 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 语句。

使用 Continue 语句生成 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 文件中的密钥。

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

结论

总之,在 C# 中 continuebreak 方法是控制循环执行的不可或缺的工具。 通过策略性地将这些语句整合到您的代码中,您可以提高其效率,可读性和可维护性。 虽然 C# 中的 goto 语句提供了一种改变执行流的机制,但其使用应谨慎对待。 在大多数情况下,结构化的控制流语句如 break, continue 或嵌套循环提供了更清晰和更可维护的解决方案。 然而,在某些特殊情况下,goto 可以被有效和安全地使用,例如在某些错误处理场景中。 与任何编程构造一样,权衡利弊并考虑代码的可读性和可维护性是决定是否使用 goto 时至关重要的。

Together with IronPDF - Comprehensive PDF Solutions library from Iron Software, developers can gain advanced skills to develop modern applications.

常见问题解答

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 生成?

控制流语句如 'continue' 和 'break' 可用于管理 PDF 生成期间的循环执行,允许开发人员根据特定条件选择性地添加内容或停止内容生成,使用 IronPDF 时。

IronPDF 的兼容性特性是什么?

IronPDF 兼容各种 .NET 版本,包括 .NET Core、.NET Standard 和 .NET Framework。它支持多种语言如 C#、VB.NET 和 F#,并与 Microsoft Visual Studio 和 JetBrains Rider 等 IDE 集成。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。