.NET幫助 C#開關模式匹配(對開發者來說是如何工作的) Curtis Chau 更新日期:8月 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 中的常見模式匹配用例 在前面的示例中,我們查看了基本語法的樣子,現在來看看實際運用。 以下代碼示例是一些實際的 PDF 任務示例,它們受益於將 IronPDF 與 C# 模式匹配結合使用。 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# switch 模式匹配應用於文檔處理? C# 中的 switch 模式匹配可用於簡化複雜的決策邏輯。結合 IronPDF 這樣的 PDF 庫,它允許開發人員更有效地管理文檔處理任務,通過精簡決策邏輯和提高代碼可讀性。 使用 switch 模式匹配相對於傳統 if-else 語句有何優勢? Switch 模式匹配提供了一種處理多個條件的更簡潔和可讀的方法,與傳統的 if-else 語句相比,它提高了 C# 代碼的可維護性,尤其是在使用 IronPDF 的複雜文檔處理任務中。 Switch 模式匹配如何促進 PDF 文檔自動化? Switch 模式匹配促進 PDF 文檔自動化,允許開發人員為管理各種文檔操作和數據類型構建更清晰的邏輯。結合使用 IronPDF,有助於自動化工作流並精簡數據提取過程。 Switch 模式匹配能否處理 C# 中的複雜文檔工作流? 是的,Switch 模式匹配非常適合處理 C# 中的複雜文檔工作流。它簡化了管理不同文檔類型和操作所需的邏輯,尤其是在使用像 IronPDF 這樣強大的庫時。 如何在 C# PDF 處理應用中實現 switch 模式匹配? 在 C# PDF 處理應用中,可以使用switch語句結合模式匹配語法來管理不同的文檔類型或處理條件。IronPDF 可用於處理實際的 PDF 操作任務。 開發人員在使用 C# 中的 switch 模式匹配時可能遇到哪些挑戰? 開發人員在使用 switch 模式匹配時可能會面臨動態或基於運行時模式的挑戰,這需要更複雜的邏輯。不過,當與像 IronPDF 這樣的庫正確結合使用時,可以顯著提高代碼效率。 Switch 模式匹配如何促進代碼可維護性? Switch 模式匹配通過提供一種清晰、簡潔的方法處理多個條件來促進代碼可維護性。這降低了複雜性,使代碼更易於理解和修改,特別是在使用 IronPDF 的大型應用中。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#整數除法(開發者如何運作) 如果您使用/運算符除以兩個整數(int類型),C#會執行整數運算,捨棄小數部分並返回整數結果 閱讀更多 C#字符串等於(它如何對開發者起作用)C#整數除法(開發者如何運...