跳至页脚内容
.NET 帮助

C# Switch 表达式(开发者如何使用)

C#不断进化,融入了提升语言表现力和增强开发者体验的功能。 在这些功能中,switch表达式尤其值得注意,是一个强大且简洁的工具,用于在单个表达式中处理多个条件。

这篇全面的探索深入剖析了C#的switch表达式,通过示例展示其语法、应用和优势。

从模式匹配和常量值到类型模式以及"switch"和"case"等关键字的使用,我们详细解读了该语言功能的多样元素。 讨论涵盖了各种模式,如常量模式、关系模式和类型模式,阐明了它们在switch表达式上下文中的角色。

此外,我们考察了switch表达式在真实场景中的整合,展示了它们的实用性,并对其语法和实现提供了清晰的说明。 欲了解switch表达式的更多内部知识,请访问这个Microsoft关于C# Switch表达式的文档

在这篇文章中,我们将通过示例演示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 文件、网址和 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表达式(它如何为开发人员工作)图1

7. 结论

C# 8.0引入的C# switch表达式作为语言中的关键演变,已成为开发人员简化条件逻辑和增强代码表达力的一个有力工具。

这次全面的探索深入到其语法、应用和优势,通过使用各种位置模式和关键字如“switch”和“case”的示例展示了其多样性。从其直观的语法和基本用法到高级声明模式和解构能力,switch表达式在设计干净、可读代码方面具有无价之宝。

与传统switch语句的对比突显了其简洁性及对如lambda表达式和表达式主体成员等表现性构造的支持。 无缝整合外部库并促进简化PDF生成的能力进一步突出了switch表达式在推进现代C#开发实践中的作用。

随着C#的持续发展,switch表达式成为该语言承诺赋予开发人员高效且有表现力的工具以有效解决问题的证明。

常见问题解答

如何在 C# 中使用切换表达式进行文档分类?

C# 中的切换表达式非常适合用于文档分类系统。例如,使用 IronPDF,您可以根据页数等属性对 PDF 文档进行分类。切换表达式的简洁语法允许高效处理和排序文档。

切换表达式比传统 C# 切换语句提供了哪些优势?

切换表达式提供更简洁的语法,去除了需要break-case语句,并支持直接值赋值。这些优势使代码更易读和维护,特别是与 IronPDF 等库结合进行 PDF 处理和分类时。

C# 中的切换表达式可以与模式匹配一起使用吗?

是的,切换表达式支持各种模式,包括模式匹配,这允许灵活处理复杂场景。可以与 IronPDF 等工具结合利用这种功能高效分类和处理文档。

C# 中切换表达式的实际应用有哪些?

切换表达式可用于文档分类、数据处理和条件逻辑管理等应用。通过 IronPDF,它们可以通过特定属性(如页数)动态处理 PDF 文档。

切换表达式如何提升 C# 代码的可读性?

切换表达式通过减少样板代码并为条件管理提供简洁语法来提高可读性。它们允许具有表达式体成员,使代码更具功能性且更易于理解,特别是与 IronPDF 等库结合使用时。

哪个版本的 C# 引入了切换表达式?

切换表达式是在 C# 8.0 中引入的。这一特性在早期版本的 C# 中不可用,因此开发人员需要确保其项目目标为 C# 8.0 或更高版本,以便有效地与 IronPDF 等库使用切换表达式。

IronPDF 与切换表达式相关的突出特性是什么?

IronPDF 的突出特性在于其能够与 C# 切换表达式集成进行 HTML 到 PDF 转换,允许开发者将 HTML 内容转换为 PDF,并基于页数等属性进行分类,使用简洁而动态的处理。

IronPDF 如何支持 HTML 到 PDF 的转换过程?

IronPDF 提供了一个 HTML 到 PDF 转换功能,保留布局和样式,实现从 web 内容无缝生成 PDF。此功能对创建报告、发票和文档特别有用,并可与 C# 切换表达式结合用于分类。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。