.NET HELP C# Switch Pattern Matching (How it Works for Developers) Jacob Mellor 更新:2025年8月5日 下載 IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 開始免費試用 法學碩士副本 法學碩士副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 在 C# 中處理 PDF 文件通常涉及處理不同類型的文件、操作或資料來源。 傳統上,開發人員可能會依賴冗長的 if-else 鏈或嵌套的 switch 語句來管理各種輸入值和類型或輸出決策。 但藉助現代 C# 特性(例如switch 模式匹配) ,您的程式碼可以變得更加優雅、易讀且易於維護。 當與IronPDF等強大的 PDF 庫結合使用時,開關模式匹配可以讓你建立更聰明、更清晰的文件處理邏輯。 在本文中,我們將探討如何將 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 結合使用? C# Switch 模式匹配(開發者如何理解):圖 1 - 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 此用法示範了表達式如何根據預期值遵循邏輯模式,將表達式與記錄中的對應屬性進行比對。 輸出大小 C# Switch 模式匹配(開發者如何理解):圖 2 - PDF 輸出的大小差異 3. 角色為基礎的 PDF,使用 Var 和非模式 使用變數模式而不是模式來處理使用者角色,同時避免出現空值或意外狀態。 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 文件。 C# Switch 模式匹配(開發者如何理解):圖 3 - 基於角色的輸出 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 關係運算子和布林表達式使程式碼簡潔明了,表達式強。 輸出 C# Switch 模式匹配(開發者工作原理):圖 4 - 基於分數的輸出 在專案中實施此模式的技巧 C# Switch 模式匹配(開發者如何理解):圖 5 - C# 模式匹配速查表 *使用記錄類型來建立乾淨且不可變的資料物件。 為了獲得更清晰的邏輯,建議優先使用 switch 表達式而不是 if-else 樹。 使用not 模式和discard 模式(_) 來忽略不相關的匹配項。 *新增預設情況*,以便及早捕捉未知輸入。 將複雜情況拆分**成輔助方法,以提高程式碼可讀性。 實際益處 *更簡潔的程式碼:*不再有嵌套過深的 if-else 或 switch case 語句區塊 更易於測試:隔離的模式案例簡化了單元測試 靈活性:新增新的輸入類型時,可以輕鬆擴展邏輯 更好地分離關注點:**僅將邏輯集中在輸入/輸出轉換上 結論:PDF邏輯現代化 switch 模式匹配不僅僅是語法上的改進,它還是編寫更安全、更具表現力的程式碼的強大範式。 結合 IronPDF 靈活的渲染功能,您可以用最少的程式碼創建更聰明、更具可擴展性的文件生成流程。 無論您是在建立報表產生器、文件預覽器或動態範本系統,都可以嘗試在 IronPDF 實作中新增模式匹配。 您很快就會看到清晰度、控制力和可維護性方面的優勢。 想親自體驗 IronPDF 嗎? 下載免費試用版,在購買授權前親自體驗 IronPDF 的強大功能。 常見問題解答 C# 切換模式匹配如何應用於文件處理? C# 中的切換模式匹配可用於簡化複雜的決策邏輯。當與 IronPDF 之類的 PDF 函式庫整合時,它可以讓開發人員透過簡化決策邏輯和改善程式碼的可讀性,更有效地管理文件處理任務。 與傳統的 if-else 語句相比,使用 switch 模式匹配有哪些優點? 相較於傳統的 if-else 語句,Switch 模式匹配提供了更簡潔、更易讀的方式來處理多重條件。它增強了 C# 程式碼的可維護性,尤其是在使用 IronPDF 處理複雜的文件處理任務時。 切換模式匹配如何促進 PDF 文件自動化? Switch 模式匹配可讓開發人員建立更簡潔的邏輯來管理各種文件動作和資料類型,從而促進 PDF 文件的自動化。與 IronPDF 搭配使用時,可協助自動化工作流程並簡化資料擷取程序。 切換模式匹配可以處理 C# 中複雜的文件工作流程嗎? 是的,切換模式匹配非常適合在 C# 中處理複雜的文件工作流程。它簡化了管理不同文件類型和動作所需的邏輯,尤其是與 IronPDF 等強大的函式庫一起使用時。 如何在 C# PDF 處理應用程式中實現切換模式匹配? 在 C# PDF 處理應用程式中,您可以透過使用具有模式匹配語法的 switch 語句來實現切換模式匹配,以管理不同的文件類型或處理條件。IronPDF 可用於處理實際的 PDF 處理任務。 開發人員在 C# 中使用切換模式匹配時可能面臨哪些挑戰? 開發人員在處理需要較複雜邏輯的動態或運行時模式時,可能會面臨切換模式匹配的挑戰。但是,如果正確地與 IronPDF 之類的函式庫搭配使用,則可大幅提升程式碼的效率。 切換模式匹配如何有助於程式碼的可維護性? 交換模式匹配透過提供清晰簡潔的方式來處理多重條件,有助於程式碼的可維護性。這降低了複雜性,使代碼更容易理解和修改,特別是在使用 IronPDF 的大型應用程式中。 Jacob Mellor 立即與工程團隊聊天 首席技術長 Jacob Mellor 是 Iron Software 的首席技術長,也是開創 C# PDF 技術的有遠見的工程師。作為 Iron Software 核心程式碼庫背後的原始開發人員,他從公司成立之初就塑造了公司的產品架構,與首席執行官 Cameron Rimington 一起將公司轉型為一家 50 多人的公司,為 NASA、Tesla 和全球政府機構提供服務。Jacob 持有曼徹斯特大學土木工程一級榮譽工程學士學位 (BEng)(1998-2001 年)。Jacob 於 1999 年在倫敦開設了他的第一家軟體公司,並於 2005 年創建了他的第一個 .NET 元件,之後,他專門解決微軟生態系統中的複雜問題。他的旗艦產品 IronPDF & Iron Suite for .NET 函式庫在全球的 NuGet 安裝量已超過 3000 萬次,他的基礎程式碼持續為全球使用的開發人員工具提供動力。Jacob 擁有 25 年的商業經驗和 41 年的編碼專業知識,他一直專注於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代的技術領導者。 相關文章 更新2025年12月11日 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 閱讀更多 更新2025年12月20日 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 閱讀更多 更新2025年12月20日 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 閱讀更多 C# String Equals (How it Works for Developers)C# Integer Division (How it Works ...
更新2025年12月11日 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 閱讀更多
更新2025年12月20日 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 閱讀更多
更新2025年12月20日 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 閱讀更多