.NET 幫助

C# 切換表示式 (適用於開發者的工作原理)

發佈 2023年12月12日
分享:

C# 不斷演進,納入了一些提昇語言表達能力和增強整體開發者體驗的特性。在這些特性中,switch 表達式尤為引人注目,作為管理多重條件的強大且簡潔的工具。

這份全面的探討深入研究了 C# switch 表達式的錯綜複雜,提供了展示其語法、應用和優勢的範例。

從模式匹配和常量值到類型模式以及使用 "switch" 和 "case" 等關鍵字,我們會逐一解釋這些語言特性的多樣元素。討論涵蓋了各種模式,如常量模式、關係模式和類型模式,並闡明它們在 switch 表達式中的角色。

此外,我們將檢視 switch 表達式在實際場景中的運用,展示其效用並闡明其語法和實現方法。如需了解更多 switch 表達式的相關知識,請訪問此處 文章在本文中,我們將通過一些switch 表達式範例並測試其使用案例。 IronPDF C# PDF 庫。

1. Switch 表達式介紹

Switch 表達式在 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
VB   C#

在此範例中,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"
'	};
VB   C#

在這種情況下,初始輸入值 shape 變數被拆解成其組成部分 (圓形或矩形)並根據類型和值生成適當的消息。

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
VB   C#

6. IronPDF 的實際應用

C# switch 表達式在現實場景中顯得尤為重要,特別是在處理多個條件或枚舉時,這在 IronPDF 的應用案例中得到了體現。讓我們探討其在文件分類系統中的實用性。

using IronPdf;
using System;
class Program
{
    static void Main()
    {
        // Simulating 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()
    {
        // Simulating 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()
		' Simulating 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
VB   C#

在這段C#程式碼片段中,IronPDF的ChromePdfRenderer被用來將模擬的HTML內容轉換成PDF文件。然後,根據PDF文件的頁數使用switch表達式進行分類。

switch表達式運用了遞歸模式,將文檔根據頁數範圍分為不同類型,如「單頁文檔」、「小型文檔」或「大型文檔」。分類後的文件隨後被保存為名為「document_output.pdf」的文件,並且在控制台中顯示消息,通知PDF創建成功及其分類結果。

這種簡潔和動態的方法展示了switch表達式的多功能性,能夠有效地應對不同情況,為基於文檔屬性進行分類提供了一個流線型的方式。

6.1. 輸出控制台

C# Switch 表達式(如何為開發人員運作) 圖1

7. 結論

C# 8.0 中引入的 C# switch 表達式作為語言的重要演變,已經成為開發者簡化條件邏輯和增強代碼表達力的有力工具。

這篇全面的探討深入研究了其語法、應用和優點,通過使用各種位置模式和如 "switch" 和 "case" 等關鍵字的例子展示了其多樣性。從直觀的語法和基本用法到高級聲明模式和解構功能,switch 表達式在撰寫乾淨、可讀性高的代碼中顯示出了無價的價值。

與傳統 switch 語句的比較突出了其簡潔性和對表達式構造的支持,包括 lambda 表達式和表達式體成員。無縫集成外部庫並促進精簡的 PDF 生成的能力,進一步強調了 switch 表達式在推進現代 C# 開發實踐中的作用。

隨著 C# 持續演進,switch 表達式作為語言致力於為開發者提供高效且富有表達力的工具來有效解決問題的見證。

< 上一頁
C# 數學(開發者如何使用)
下一個 >
NUnit 或 xUnit .NET Core(開發人員如何使用)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >