.NET 帮助 C# Switch 模式匹配(开发者用法) Curtis Chau 已更新:八月 5, 2025 Download IronPDF NuGet 下载 DLL 下载 Windows 安装程序 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 在 C# 中处理 PDF 文件通常涉及处理不同类型的文档、操作或数据源。 传统上,开发人员可能依赖长长的 if-else 链或嵌套的 switch 语句来管理各种输入值和类型或输出决策。 但通过现代 C# 功能,如switch 模式匹配,您的代码可以变得更加优雅、可读和易于维护。 与像 IronPDF 这样强大的 PDF 库结合使用时,switch 模式匹配允许您为文档处理构建更智能、更简洁的逻辑。 在本文中,我们将探讨如何使用 C# 的高级模式匹配功能(例如类型模式、属性模式和关系模式)与 IronPDF 一起简化您的 PDF 生成工作流。 什么是 C# 中的 Switch 模式匹配? Switch 模式匹配是 C# 7 中引入的一个特性,并在后续版本中不断改进。 与仅匹配常量值的传统 switch 语句不同,模式匹配使您能够在单个表达式中评估类型、属性和条件。 以下示例演示了此功能的工作原理。 示例语法 switch (input) { case int i when i > 0: Console.WriteLine("Positive integer"); break; case string s: Console.WriteLine($"It's a string: {s}"); break; default: Console.WriteLine("Unknown type"); break; } switch (input) { case int i when i > 0: Console.WriteLine("Positive integer"); break; case string s: Console.WriteLine($"It's a string: {s}"); break; default: Console.WriteLine("Unknown type"); break; } Select Case input 'INSTANT VB TODO TASK: The following 'case' pattern variable is not converted by Instant VB: 'ORIGINAL LINE: case int i when i > 0: Case Integer i [when] i > 0 Console.WriteLine("Positive integer") 'INSTANT VB TODO TASK: The following 'case' pattern variable is not converted by Instant VB: 'ORIGINAL LINE: case string s: Case String s Console.WriteLine($"It's a string: {s}") Case Else Console.WriteLine("Unknown type") End Select $vbLabelText $csharpLabel 此代码使用类型模式、关系运算符和空常量模式简明处理多个情况。 这项技术通过更简洁的语法显着提高了代码可读性,并支持更复杂的逻辑。 为什么将 Switch 模式匹配与 IronPDF 结合使用? IronPDF 是一个强大的 .NET 组件,用于从 HTML、图像或原始文本生成和操作 PDF。 许多实际应用涉及处理不同模式的输入:一些文档可能来自 URL,其他来自 HTML 字符串,还有一些来自文件上传。 不再使用笨拙的 if 条件测试表达式,switch 模式匹配使您能够有效支持基于模式的逻辑。 它允许您定义应用程序如何响应不同的对象类型、指定的常量甚至布尔表达式——使用输入表达式本身来驱动工作流。 IronPDF 中使用模式匹配的常见用例 在之前的示例中,我们看到了基本语法的样子,但现在让我们看看它的实际应用。 以下代码示例是一些结合 IronPDF 和 C# 模式匹配受益的实际 PDF 任务。 1. 使用类型和属性模式处理多种输入格式 假设您的方法接受多种输入格式:HTML、URI 或本地 .html 文件。利用类型模式、属性模式和空模式,您可以轻松区分这些情况。 using System; using System.IO; using IronPdf; class Program { static void Main() { object input = new Uri("https://example.com"); // Try changing this to: "<html><body>Hello</body></html>" or new FileInfo("sample.html") var renderer = new ChromePdfRenderer(); PdfDocument pdfDoc = input switch { string html when html.StartsWith("<html>") => renderer.RenderHtmlAsPdf(html), Uri url => renderer.RenderUrlAsPdf(url.ToString()), FileInfo { Extension: ".html" } file => renderer.RenderHtmlAsPdf(File.ReadAllText(file.FullName)), null => throw new ArgumentNullException("Input was null."), _ => throw new ArgumentException("Unsupported input type for PDF conversion.") }; pdfDoc.SaveAs("example-input-types.pdf"); Console.WriteLine("PDF created: example-input-types.pdf"); } } using System; using System.IO; using IronPdf; class Program { static void Main() { object input = new Uri("https://example.com"); // Try changing this to: "<html><body>Hello</body></html>" or new FileInfo("sample.html") var renderer = new ChromePdfRenderer(); PdfDocument pdfDoc = input switch { string html when html.StartsWith("<html>") => renderer.RenderHtmlAsPdf(html), Uri url => renderer.RenderUrlAsPdf(url.ToString()), FileInfo { Extension: ".html" } file => renderer.RenderHtmlAsPdf(File.ReadAllText(file.FullName)), null => throw new ArgumentNullException("Input was null."), _ => throw new ArgumentException("Unsupported input type for PDF conversion.") }; pdfDoc.SaveAs("example-input-types.pdf"); Console.WriteLine("PDF created: example-input-types.pdf"); } } Imports System Imports System.IO Imports IronPdf Friend Class Program Shared Sub Main() Dim input As Object = New Uri("https://example.com") ' Try changing this to: "<html><body>Hello</body></html>" or new FileInfo("sample.html") Dim renderer = New ChromePdfRenderer() 'INSTANT VB TODO TASK: The following 'switch expression' was not converted by Instant VB: ' PdfDocument pdfDoc = input switch ' { ' string html when html.StartsWith("<html>") => renderer.RenderHtmlAsPdf(html), ' Uri url => ' renderer.RenderUrlAsPdf(url.ToString()), ' FileInfo { Extension: ".html" } file => ' renderer.RenderHtmlAsPdf(File.ReadAllText(file.FullName)), ' null => throw new ArgumentNullException("Input was null."), ' _ => throw new ArgumentException("Unsupported input type for PDF conversion.") ' }; pdfDoc.SaveAs("example-input-types.pdf") Console.WriteLine("PDF created: example-input-types.pdf") End Sub End Class $vbLabelText $csharpLabel 在这里,属性模式 (FileInfo { Extension: ".html" }) 和空常量匹配 (case null) 使逻辑更具表达性和健壮性。 2. 使用位置和声明模式动态格式化 PDF 假设您在使用包含格式字符串的 PdfRequest 记录。 您可以应用位置模式、声明模式和字符串常量来自定义 PDF 格式。 using System; using IronPdf; public record PdfRequest(string Title, string Content, string Format); class Program { static void Main() { PdfRequest request = new("My Report", "<h1>Monthly Report</h1><p>Generated by IronPDF.</p>", "A4"); var renderer = new ChromePdfRenderer(); // Use fully qualified enum to avoid IronWord conflict renderer.RenderingOptions = request switch { PdfRequest { Format: "A4" } => new IronPdf.ChromePdfRenderOptions { PaperSize = IronPdf.Rendering.PdfPaperSize.A4 }, PdfRequest { Format: "Letter" } => new IronPdf.ChromePdfRenderOptions { PaperSize = IronPdf.Rendering.PdfPaperSize.Letter }, _ => new IronPdf.ChromePdfRenderOptions { PaperSize = IronPdf.Rendering.PdfPaperSize.Legal // Fallback } }; var pdf = renderer.RenderHtmlAsPdf(request.Content); pdf.SaveAs("example-formatted.pdf"); Console.WriteLine("PDF created: example-formatted.pdf"); } } using System; using IronPdf; public record PdfRequest(string Title, string Content, string Format); class Program { static void Main() { PdfRequest request = new("My Report", "<h1>Monthly Report</h1><p>Generated by IronPDF.</p>", "A4"); var renderer = new ChromePdfRenderer(); // Use fully qualified enum to avoid IronWord conflict renderer.RenderingOptions = request switch { PdfRequest { Format: "A4" } => new IronPdf.ChromePdfRenderOptions { PaperSize = IronPdf.Rendering.PdfPaperSize.A4 }, PdfRequest { Format: "Letter" } => new IronPdf.ChromePdfRenderOptions { PaperSize = IronPdf.Rendering.PdfPaperSize.Letter }, _ => new IronPdf.ChromePdfRenderOptions { PaperSize = IronPdf.Rendering.PdfPaperSize.Legal // Fallback } }; var pdf = renderer.RenderHtmlAsPdf(request.Content); pdf.SaveAs("example-formatted.pdf"); Console.WriteLine("PDF created: example-formatted.pdf"); } } Imports System Imports IronPdf 'INSTANT VB TODO TASK: C# 'records' are not converted by Instant VB: 'public record PdfRequest(string Title, string Content, string Format) Friend Class Program Shared Sub Main() Dim request As New PdfRequest("My Report", "<h1>Monthly Report</h1><p>Generated by IronPDF.</p>", "A4") Dim renderer = New ChromePdfRenderer() ' Use fully qualified enum to avoid IronWord conflict 'INSTANT VB TODO TASK: The following 'switch expression' was not converted by Instant VB: ' renderer.RenderingOptions = request switch ' { ' PdfRequest { Format: "A4" } => new IronPdf.ChromePdfRenderOptions ' { ' PaperSize = IronPdf.Rendering.PdfPaperSize.A4 ' }, ' PdfRequest { Format: "Letter" } => new IronPdf.ChromePdfRenderOptions ' { ' PaperSize = IronPdf.Rendering.PdfPaperSize.Letter ' }, ' _ => new IronPdf.ChromePdfRenderOptions ' { ' PaperSize = IronPdf.Rendering.PdfPaperSize.Legal // Fallback ' } ' }; Dim pdf = renderer.RenderHtmlAsPdf(request.Content) pdf.SaveAs("example-formatted.pdf") Console.WriteLine("PDF created: example-formatted.pdf") End Sub End Class $vbLabelText $csharpLabel 这种用法展示了如何表达式匹配记录中的相应属性,按照基于预期值的逻辑模式进行。 输出尺寸 3. 使用 Var 和 Not 模式生成基于角色的 PDF 使用 var 模式和 not 模式来处理用户角色,同时避免空或意外状态。 using System; using IronPdf; public abstract record UserRole; public record Admin(string Email) : UserRole; public record Viewer(string Email) : UserRole; public record Guest() : UserRole; class Program { static void Main() { UserRole currentUser = new Admin("admin@example.com"); // Try changing to Viewer or Guest var pdf = currentUser switch { Admin { Email: var email } => new ChromePdfRenderer().RenderHtmlAsPdf($"<h1>Admin Dashboard</h1><p>Email: {email}</p>"), Viewer => new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Viewer Summary</h1><p>Access limited.</p>"), Guest => new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Guest Mode</h1><p>Please sign in.</p>"), not null => throw new UnauthorizedAccessException("Unknown role type."), null => throw new ArgumentNullException("Role cannot be null.") }; pdf.SaveAs("example-role.pdf"); Console.WriteLine("PDF created: example-role.pdf"); } } using System; using IronPdf; public abstract record UserRole; public record Admin(string Email) : UserRole; public record Viewer(string Email) : UserRole; public record Guest() : UserRole; class Program { static void Main() { UserRole currentUser = new Admin("admin@example.com"); // Try changing to Viewer or Guest var pdf = currentUser switch { Admin { Email: var email } => new ChromePdfRenderer().RenderHtmlAsPdf($"<h1>Admin Dashboard</h1><p>Email: {email}</p>"), Viewer => new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Viewer Summary</h1><p>Access limited.</p>"), Guest => new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Guest Mode</h1><p>Please sign in.</p>"), not null => throw new UnauthorizedAccessException("Unknown role type."), null => throw new ArgumentNullException("Role cannot be null.") }; pdf.SaveAs("example-role.pdf"); Console.WriteLine("PDF created: example-role.pdf"); } } Imports System Imports IronPdf Public MustOverride ReadOnly Property UserRole() As record public record Admin(String Email) : UserRole public record Viewer(String Email) : UserRole public record Guest() : UserRole Dim Program As class If True Then 'INSTANT VB TODO TASK: Local functions are not converted by Instant VB: ' static void Main() ' { ' UserRole currentUser = New Admin("admin@example.com"); ' Try changing to Viewer or Guest ''INSTANT VB TODO TASK: The following 'switch expression' was not converted by Instant VB: '' var pdf = currentUser switch '' { '' Admin { Email: var email } => new ChromePdfRenderer().RenderHtmlAsPdf($"<h1>Admin Dashboard</h1><p>Email: {email}</p>"), '' Viewer => '' new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Viewer Summary</h1><p>Access limited.</p>"), '' Guest => '' new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Guest Mode</h1><p>Please sign in.</p>"), '' not null => '' throw new UnauthorizedAccessException("Unknown role type."), '' null => '' throw new ArgumentNullException("Role cannot be null.") '' }; ' pdf.SaveAs("example-role.pdf"); ' Console.WriteLine("PDF created: example-role.pdf"); ' } End If $vbLabelText $csharpLabel 这种结构提高了安全性和代码可读性,同时利用了临时变量声明,如 var email。 以下图像显示了根据不同输入值创建的不同 PDF 文件。 4. 基于用户数据的关系模式匹配 需要根据用户级别生成不同的 PDF 吗? 尝试使用两个关系模式来测试输入是否在某个范围内。 using System; using IronPdf; class Program { static void Main() { int userScore = 85; // Try other values: 45, 70, 101 string message = userScore switch { < 60 => "Needs Improvement", >= 60 and < 80 => "Satisfactory", >= 80 and <= 100 => "Excellent", _ => "Invalid score" }; var html = $"<h1>Score Report</h1><p>Score: {userScore}</p><p>Result: {message}</p>"; var pdf = new ChromePdfRenderer().RenderHtmlAsPdf(html); pdf.SaveAs("example-score.pdf"); Console.WriteLine("PDF created: example-score.pdf"); } } using System; using IronPdf; class Program { static void Main() { int userScore = 85; // Try other values: 45, 70, 101 string message = userScore switch { < 60 => "Needs Improvement", >= 60 and < 80 => "Satisfactory", >= 80 and <= 100 => "Excellent", _ => "Invalid score" }; var html = $"<h1>Score Report</h1><p>Score: {userScore}</p><p>Result: {message}</p>"; var pdf = new ChromePdfRenderer().RenderHtmlAsPdf(html); pdf.SaveAs("example-score.pdf"); Console.WriteLine("PDF created: example-score.pdf"); } } Imports System Imports IronPdf Friend Class Program Shared Sub Main() Dim userScore As Integer = 85 ' Try other values: 45, 70, 101 'INSTANT VB TODO TASK: The following 'switch expression' was not converted by Instant VB: ' string message = userScore switch ' { ' < 60 => "Needs Improvement", ' >= 60 and < 80 => "Satisfactory", ' >= 80 and <= 100 => "Excellent", ' _ => "Invalid score" ' }; Dim html = $"<h1>Score Report</h1><p>Score: {userScore}</p><p>Result: {message}</p>" Dim pdf = (New ChromePdfRenderer()).RenderHtmlAsPdf(html) pdf.SaveAs("example-score.pdf") Console.WriteLine("PDF created: example-score.pdf") End Sub End Class $vbLabelText $csharpLabel 关系运算符和布尔表达式使代码简洁而富有表现力。 输出 在您的项目中实施此模式的提示 使用记录类型来清晰和不可变的数据对象。 更喜欢使用 switch 表达式而不是 if-else 树以获得更清晰的逻辑。 使用not 模式和丢弃模式(_)来忽略不相关匹配。 使用添加默认案例来尽早处理未知输入。 将复杂情况分解到辅助方法中以提高可读性。 实际好处 更简洁的代码:不再需要深度嵌套的 if-else 或 switch-case 块 更容易测试:独立的模式案例简化了单元测试 灵活性:在添加新输入类型时轻松扩展逻辑 更好的关注点分离:仅专注于输入/输出转换的逻辑 结论:现代化您的 PDF 逻辑 Switch 模式匹配不仅仅是语法改进,它是撰写更安全、更具表达力代码的强大范式。 结合 IronPDF 的灵活渲染能力,您可以通过极少代码创建更智能、更可扩展的文档生成管道。 无论您是在构建报告生成器、文档预览器还是动态模板系统,尝试在您的 IronPDF 实现中添加模式匹配。 您将快速看到在清晰性、控制和可维护性方面的好处。 想亲自尝试 IronPDF 吗? 下载免费试用版,在购买许可证前亲自尝试 IronPDF 的强大功能。 常见问题解答 C# 开关模式匹配如何应用于文档处理? C# 中的开关模式匹配可用于简化复杂的决策逻辑。与 IronPDF 等 PDF 库集成使用时,它允许开发者更有效地管理文档处理任务,通过简化决策逻辑和提高代码可读性。 使用开关模式匹配优于传统 if-else 语句的优势是什么? 与传统 if-else 语句相比,开关模式匹配提供了一种更简洁、更易读的方式来处理多条件。它增强了 C# 代码的可维护性,尤其是在使用 IronPDF 进行复杂的文档处理任务时。 开关模式匹配如何促进 PDF 文档自动化? 开关模式匹配通过使开发者能够构建更清晰的逻辑来管理各种文档操作和数据类型,从而促进 PDF 文档自动化。在 IronPDF 的助力下,它有助于自动化工作流程和简化数据提取过程。 开关模式匹配能够处理 C# 中的复杂文档工作流程吗? 是的,开关模式匹配非常适合处理 C# 中的复杂文档工作流程。它简化了管理不同文档类型和操作所需的逻辑,特别是在与像 IronPDF 这样的强大库一起使用时。 如何在 C# PDF 处理应用程序中实现开关模式匹配? 在 C# PDF 处理应用程序中,可以通过使用带有模式匹配语法的 switch 语句来管理不同文档类型或处理条件来实现开关模式匹配。IronPDF 可以用于实际的 PDF 操作任务。 开发者在 C# 中使用开关模式匹配时可能面临哪些挑战? 开发者在处理需要更复杂逻辑的动态或运行时模式时,可能会面临使用开关模式匹配的挑战。然而,正确地与像 IronPDF 这样的库一起使用时,它可以显著提高代码效率。 开关模式匹配如何促进代码的可维护性? 开关模式匹配通过提供一种清晰、简洁的方式来处理多条件,促进了代码的可维护性。这减少了复杂性,并使代码更易于理解和修改,特别是在使用 IronPDF 的大型应用程序中。 Curtis Chau 立即与工程团队聊天 技术作家 Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。 相关文章 已更新九月 4, 2025 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多 已更新九月 4, 2025 C# String Equals(开发者用法) 与强大的 PDF 库 IronPDF 结合使用,切换模式匹配允许您为文档处理构建更智能、更简洁的逻辑。 阅读更多 已更新八月 5, 2025 C# 整数除法 (开发者用法) 如果您使用 / 运算符除以两个整数(int 类型),C# 会执行整数算术,通过舍弃小数部分来返回整数结果。 阅读更多 C# String Equals(开发者用法)C# 整数除法 (开发者用法)
已更新九月 4, 2025 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多