C# 切換表達式(開發者的工作原理)
C# 經過不斷的演進,加入了提升語言表達力和增強整體開發者經驗的功能。 在這些功能中,switch 表達式尤其值得注意,它是在單一表達式中管理多個條件的有效且簡潔的工具。
本書全面探討 C# 切換表達式的複雜性,提供範例強調其語法、應用和優點。
從模式匹配和常數值到類型模式,以及"switch"和"case"等關鍵字的使用,我們將在這種語言功能的多樣元素中遊刃有餘。 討論內容包含各種模式,例如常數模式、關係模式和類型模式,並闡明它們在切換表達式上下文中的作用。
此外,我們還會檢視切換表達式在真實世界情境中的融入,展示其效用並說明其語法與實作。 如需更多關於切換表達式的內部知識,請造訪此 Microsoft Documentation on C# Switch Expressions。
在這篇文章中,我們將透過 switch 表達式的範例,並使用 IronPDF C# PDF Library 測試其使用情況。
1.Switch Expression 簡介
C# 8.0 引入的 switch 表達式代表了開發人員處理條件邏輯方式的範式轉變。 傳統上,switch 語句是根據不同值進行分支的最佳選擇,但在使用關鍵字時,它在語氣和彈性方面有其限制。 轉換表達式透過提供簡潔的語法來解決這些問題,讓程式碼更具表現力和功能性。
在其最簡單的形式中,switch 表達式類似於傳統的 switch 語句,但用途更廣泛。它會評估一個表達式,並根據該表達式的值來選擇分支。 這種範式的轉變能讓開發人員寫出更乾淨、更易讀的程式碼,並減少模板。
2.語法和基本用法
C# switch 表達式的語法很直覺,熟悉傳統 switch 語句的開發人員很容易採用。 以下是一個基本範例:
string result = input switch
{
"case1" => "Result for case 1",
"case2" => "Result for case 2",
_ => "Default result for case label"
};
string result = input switch
{
"case1" => "Result for case 1",
"case2" => "Result for case 2",
_ => "Default result for case label"
};
Dim tempVar As String
Select Case input
Case "case1"
tempVar = "Result for case 1"
Case "case2"
tempVar = "Result for case 2"
Case Else
tempVar = "Default result for case label"
End Select
Dim result As String = tempVar
在這個範例中,input 變數針對多種情況進行評估。 如果模式與指定的其中一種情況相符,則會將相對應的結果指定給 result 變數。 下劃線 (_) 代表預設的可選情況,類似於傳統 switch 語句中的 default 關鍵字。
切換表達式支援多種模式,包括常數模式、類型模式、關係模式等,使其成為處理複雜情況的多用途工具。 在處理枚舉時尤其有用,可避免重複的 case 陳述。
3.進階模式與解構
切換表達法的優勢之一在於它能夠處理進階模式和解構。 這可讓開發人員簡明扼要地從物件、陣列和模式中抽取數值。 請考慮以下開關表達式的範例:
var result = shape switch
{
Circle c => $"Circle with radius {c.Radius}",
Rectangle r => $"Rectangle with dimensions {r.Length}x{r.Width}",
_ => "Unknown shape"
};
var result = shape switch
{
Circle c => $"Circle with radius {c.Radius}",
Rectangle r => $"Rectangle with dimensions {r.Length}x{r.Width}",
_ => "Unknown shape"
};
'INSTANT VB TODO TASK: The following 'switch expression' was not converted by Instant VB:
'var result = shape switch
'{
' Circle c => $"Circle with radius {c.Radius}",
' Rectangle r => $"Rectangle with dimensions {r.Length}x{r.Width}",
' _ => "Unknown shape"
'};
在本例中,初始輸入值、shape 變數會被解構為其元件 (Circle 或 Rectangle),並根據類型和值產生適當的訊息。
4. Switch表達式與Switch語句
雖然開關表達式與傳統的類開關語意模式有相似之處,但它有幾個優點。 switch 關鍵字的表達方式更為簡潔,不需要 break-case 語句,並可減少模板程式碼。 此外,還可直接在表達式中進行數值的指定,讓程式碼更具表現力。
另一個值得注意的特點是可以在 lambda 表達式中使用來自 switch 表達式的表達式,或在方法或屬性中作為表達式為主的成員的一部分,有助於更功能化的程式設計風格。
此外,轉換表達式鼓勵使用常數模式匹配,提供更自然、更強大的方式來處理不同的情況。
5.效能考量與限制
雖然切換表達方式帶來許多好處,但關鍵是要注意效能方面的考量。 在某些情況下,轉換語句可能更具效能,尤其是在處理大量案例時。 開發人員應評估其應用程式的特定需求,並據此選擇適當的結構。
另一個需要注意的地方是 switch 表達式不能完全取代 switch 語句。 在某些情況下,switch 語句的 fall-through 行為可能是首選。
此外,切換表達式僅在 C# 8.0 及更高版本中可用,因此針對早期版本的專案將無法使用此功能。
IronPDF 的突出功能是其HTML 至 PDF 轉換功能,可保留所有版面和樣式。 它允許從網頁內容生成 PDF,是報告、發票和文件的理想選擇。 HTML 檔案、URL 和 HTML 字串可以毫不費力地轉換成 PDF。
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
Imports IronPdf
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim renderer = New ChromePdfRenderer()
' 1. Convert HTML String to PDF
Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")
' 2. Convert HTML File to PDF
Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")
' 3. Convert URL to PDF
Dim url = "http://ironpdf.com" ' Specify the URL
Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
pdfFromUrl.SaveAs("URLToPDF.pdf")
End Sub
End Class
6.IronPDF 的實際應用
C# switch 表達式的應用在實際情境中具有顯著的影響力,尤其是在管理多重條件或枚舉時,例如 IronPDF 的使用案例。 讓我們來探討它在文件分類系統中的實用性。
using IronPdf;
using System;
class Program
{
static void Main()
{
// Simulate HTML content for the PDF document
string htmlContent = GetHtmlContent();
// Creating IronPDF Document
var pdfDocument = new ChromePdfRenderer();
// Converting HTML to PDF
var pdf = pdfDocument.RenderHtmlAsPdf(htmlContent);
// Classifying the document based on the page count
string classification = pdf switch
{
{ PageCount: 1 } => "Single Page Document",
{ PageCount: >= 2 and <= 10 } => "Small Document",
{ PageCount: > 10 } => "Large Document",
_ => "Unknown Classification"
};
// Save the PDF to a file
pdf.SaveAs("document_output.pdf");
// Displaying the classification result
Console.WriteLine($"PDF created successfully. Document Classification: {classification}");
}
static string GetHtmlContent()
{
// In a real-world scenario, you would obtain the HTML content from an actual source.
// For the sake of this example, we'll create a simple HTML string.
string htmlContent = "<html><body><h1>Hello IronPDF!</h1><p>This is a sample HTML content.</p></body></html>";
return htmlContent;
}
}
using IronPdf;
using System;
class Program
{
static void Main()
{
// Simulate HTML content for the PDF document
string htmlContent = GetHtmlContent();
// Creating IronPDF Document
var pdfDocument = new ChromePdfRenderer();
// Converting HTML to PDF
var pdf = pdfDocument.RenderHtmlAsPdf(htmlContent);
// Classifying the document based on the page count
string classification = pdf switch
{
{ PageCount: 1 } => "Single Page Document",
{ PageCount: >= 2 and <= 10 } => "Small Document",
{ PageCount: > 10 } => "Large Document",
_ => "Unknown Classification"
};
// Save the PDF to a file
pdf.SaveAs("document_output.pdf");
// Displaying the classification result
Console.WriteLine($"PDF created successfully. Document Classification: {classification}");
}
static string GetHtmlContent()
{
// In a real-world scenario, you would obtain the HTML content from an actual source.
// For the sake of this example, we'll create a simple HTML string.
string htmlContent = "<html><body><h1>Hello IronPDF!</h1><p>This is a sample HTML content.</p></body></html>";
return htmlContent;
}
}
Imports IronPdf
Imports System
Friend Class Program
Shared Sub Main()
' Simulate HTML content for the PDF document
Dim htmlContent As String = GetHtmlContent()
' Creating IronPDF Document
Dim pdfDocument = New ChromePdfRenderer()
' Converting HTML to PDF
Dim pdf = pdfDocument.RenderHtmlAsPdf(htmlContent)
' Classifying the document based on the page count
'INSTANT VB TODO TASK: The following 'switch expression' was not converted by Instant VB:
' string classification = pdf switch
' {
' { PageCount: 1 } => "Single Page Document",
' { PageCount: >= 2 and <= 10 } => "Small Document",
' { PageCount: > 10 } => "Large Document",
' _ => "Unknown Classification"
' };
' Save the PDF to a file
pdf.SaveAs("document_output.pdf")
' Displaying the classification result
Console.WriteLine($"PDF created successfully. Document Classification: {classification}")
End Sub
Private Shared Function GetHtmlContent() As String
' In a real-world scenario, you would obtain the HTML content from an actual source.
' For the sake of this example, we'll create a simple HTML string.
Dim htmlContent As String = "<html><body><h1>Hello IronPDF!</h1><p>This is a sample HTML content.</p></body></html>"
Return htmlContent
End Function
End Class
在此 C# 程式碼片段中,利用 IronPDF 的 ChromePdfRenderer 將模擬的 HTML 內容轉換成 PDF 文件。 翻譯後的 PDF 將根據頁數使用切換表達式進行分類。
切換表達式採用遞歸模式,根據特定的頁數範圍,將文件歸類為不同類型,例如"單頁文件"、"小型文件"或"大型文件"。 分類後的文件隨後會儲存到一個名為"document_output.pdf"的檔案中,控制台訊息會傳達成功建立的 PDF 及其分類結果。
這種簡潔且動態的方式展現了切換表達式在有效處理不同情境時的多樣性,提供了一種根據文件屬性來分類的簡化方式。
6.1.輸出控制台

7.結論
C# switch 表達式在 C# 8.0 中推出,是 C# 語言的重要演進,已成為開發人員簡化條件邏輯和增強程式碼表達力的引人注目的工具。
這份全面的探討深入其語法、應用和優勢,並透過使用各種位置模式和關鍵字 (如 "switch" 和 "case") 的範例來展示其多功能性。從直覺的語法和基本用法,到進階的宣告模式和解構功能,switch 表達式在編寫乾淨、可讀的程式碼方面已被證明是無價之寶。
與傳統 switch 語句的比較,強調其簡潔性以及對具表達力構造的支援,包括 lambda 表達式和具表達力的成員。 能夠與外部程式庫無縫整合,並有助於簡化 PDF 的產生,這進一步強調了切換表達式在推動現代 C# 開發實務中的作用。
隨著 C# 的持續發展,轉換表達方式證明了該語言致力於為開發人員提供有效解決問題的高效且具表達力的工具。
常見問題解答
如何在 C# 中使用 switch 表達式進行文檔分類?
C# 中的 switch 表達式非常適合文檔分類系統。例如,使用 IronPDF,您可以根據頁數等屬性對 PDF 文檔進行分類。switch 表達式簡潔的語法允許高效處理和排序文檔。
switch 表達式比傳統的 C# switch 語句有什麼優勢?
switch 表達式提供了更簡潔的語法,消除了需要 break-case 語句並支持直接值賦值。這些優勢導致代碼更具可讀性和可維護性,特別是與 IronPDF 等庫集成進行 PDF 處理和分類時。
switch 表達式能否與 C# 的模式匹配一起使用?
是的,switch 表達式支持多種模式,包括模式匹配,允許處理複雜場景的多功能性。此功能可與 IronPDF 等工具結合使用,以高效分類和處理文檔。
C# 中 switch 表達式的一些實際應用有哪些?
switch 表達式可以應用於文檔分類、數據處理和條件邏輯管理等應用中。使用 IronPDF,它們可以根據特定屬性(如頁數)動態處理 PDF 文檔。
switch 表達式如何增強 C# 代碼的可讀性?
switch 表達式通過減少樣板代碼和提供條件管理的簡潔語法來增強可讀性。它們允許表達式體成員,讓代碼更具功能性且易於理解,特別是與 IronPDF 等庫結合使用時。
哪個版本的 C# 引入了 switch 表達式?
switch 表達式是 C# 8.0 中引入的。此功能在早期版本的 C# 中不可用,因此開發人員需要確保他們的項目針對 C# 8.0 或更高版本,以便與 IronPDF 等庫一起有效利用 switch 表達式。
IronPDF 與 switch 表達式的突出功能是什麼?
IronPDF 的突出功能是其能夠與 C# switch 表達式集成進行 HTML 到 PDF 的轉換,允許開發人員將 HTML 內容轉換為 PDF,並根據屬性如頁數進行分類,使用簡潔和動態的處理方式。
IronPDF 如何支持 HTML 到 PDF 的轉換過程?
IronPDF 提供 HTML 到 PDF 的轉換功能,保留佈局和樣式,從而實現從網頁內容到 PDF 的無縫生成。此功能對於創建報告、發票和文檔特別有用,並且可以通過 C# switch 表達式進行分類來增強。



