跳過到頁腳內容
.NET幫助

C# 切換表達式(開發者的工作原理)

C# 不斷發展,整合特性以提升語言的表達能力並增強整體開發者體驗。 在這些特性中,switch 表達式特別值得注意,作為一種強大而簡潔的工具,用於在單一表達式中管理多個條件。

這項全面的探索深入剖析 C# switch 表達式的複雜性,提供突出其語法、應用及優勢的示例。

從模式匹配和常數值到類型模式及使用像"switch"和"case"這樣的關鍵字,我們遍歷該語言特性的多樣元素。 討論包含各種模式,例如常數模式、關係模式和類型模式,闡明其在 switch 表達式上下文中的作用。

此外,我們檢查了在現實場景中配合使用 switch 表達式,展示其效用並提供對其語法和實施的清晰理解。 如需有關 switch 表達式的更多內幕知識,請訪問本Microsoft C# Switch Expressions 文檔

在本文中,我們將透過示範 switch 表達式及測試其在使用IronPDF C# PDF 庫時的用案例。

1. Switch 表達式介紹

在 C# 8.0 中引入的 switch 表達式,代表了開發者處理條件邏輯方式的範式轉變。 傳統上,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
$vbLabelText   $csharpLabel

在此示例中,input 變量將與多個案例進行評估。 如果該模式匹配到指定的案例之一,則相應的結果將被賦予到 result 變量。 下劃線 (_) 代表默認的可選案例,類似於傳統 switch 語句中的 default 關鍵字。

switch 表達式支持廣泛的模式,包括常數模式、類型模式、關係模式等,使其成為處理複雜場景的多功能工具。 它在處理枚舉時尤其有用,避免了重複的 case 語句的需求。

3. 高級模式和解構

switch 表達式的優勢之一在於其能夠處理高級模式和解構。 這允許開發者通過簡潔的方式從對象、數組和模式中提取值。 考慮以下 switch 表達式示例:

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"
'};
$vbLabelText   $csharpLabel

在此情況下,初始輸入值,shape 變量被解構為其組件(Circle 或 Rectangle),並根據類型和值生成適當的信息。

4. Switch 表達式 vs. Switch 語句

尽管 switch 表达式在语义上与传统 switch 类似,但它具有几个优势。 switch 关键字表达式更简洁,消除了对 break-case 语句的需求,并减少了样板代码。 它还允许在表达式中直接赋值,使代码更具表达性。

另一个值得注意的特性是能够在 lambda 表达式中使用 switch 表达式或作为方法或属性中的表达式主体成员的一部分,促进更具功能风格的程序设计。

此外,switch 表达式鼓励使用常量模式匹配,提供了一种更自然和强大的方式来处理不同的情况。

5. 性能考量和限制

儘管 switch 表達式帶來許多好處,但要意識到性能考量是至關重要的。 在某些場景下,尤其是在處理大量案例時,switch 語句可能表現得更高效。 開發者應評估應用的具體需求並相應選擇適當的構造。

需要注意的另一點是,switch 表達式無法完全取代 switch 語句。 在一些情況下,帶有階段行為的 switch 語句可能是更好的選擇。

此外,switch 表達式僅在 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
$vbLabelText   $csharpLabel

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
$vbLabelText   $csharpLabel

在這個 C# 代碼片段中,IronPDF 的 ChromePdfRenderer 被用於將模擬的 HTML 內容轉換為 PDF 文件。 生成的 PDF 隨後根據其頁面數使用 switch 表達式進行分類。

switch 表達式使用遞歸模式根據特定的頁數範圍將文檔分類為不同類型,例如「單頁文檔」、「小型文檔」或「大型文檔」。 分類後的文檔隨後保存到名為「document_output.pdf」的文件中,並通過控制台信息確認成功創建 PDF 及其分類結果。

該簡潔且動態的方法展示了 switch 表達式在有效處理不同場景中的多功能性,提供了一種基於其屬性對文檔進行分類的簡化方式。

6.1. 輸出控制台

C# Switch Expression (開發者如何使用) 圖1

7. 結論

C# switch 表達式,在 C# 8.0 中作為語言的重要演進而引入,已成為開發者流線型條件邏輯及增強代碼表達力的強大工具。

這項全面探索深入解析其語法、應用及優勢,通過使用各種位置模式和關鍵字如"switch"和"case"的示例展示其多樣性。從其直觀的語法和基本用途到高級聲明模式和解構功能,switch 表達式在編寫清晰、可讀代碼方面無疑是無價的。

與傳統 switch 語句的比較突顯其簡潔性及對表達構造的支持,包括 lambda 表達式和表達式主體成員。 與外部庫的無縫集成以及對流線型 PDF 生成的貢獻進一步強調了 switch 表達式在推進現代 C# 開發實踐中的作用。

隨著 C# 的不斷發展,switch 表達式作為語言致力於提供高效且有表達力的工具以促進有效問題解決的見證。

常見問題解答

如何在 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 表達式進行分類來增強。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。