.NET 帮助

C# 切换表达式(它是如何为开发人员工作的)

发布 2023年十二月12日
分享:

C# 经历了不断的演变,融入了各种功能,提升了语言的表现力,增强了开发人员的整体体验。在这些功能中,开关表达式尤其值得一提,它是在单个表达式中管理多个条件的有效而简洁的工具。

这本书全面探讨了 C# 切换表达式的复杂性,并通过示例强调了其语法、应用和优势。

从模式匹配和常量值到类型模式以及 "switch "和 "case "等关键字的使用,我们将对这一语言特点的各种元素进行导航。讨论包括各种模式,如常量模式、关系模式和类型模式,并阐明它们在开关表达式上下文中的作用。

此外,我们还探讨了如何将开关表达式应用到实际场景中,展示了它们的实用性,并阐明了它们的语法和实现方法。有关开关表达式的更多内部知识,请访问 .

在本文中,我们将通过开关表达式的示例,使用 IronPDF C# PDF 库

1.开关表达式简介

C# 8.0 中引入的 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#

在本例中,输入变量将针对多个情况进行评估。如果模式匹配指定的情况之一,相应的结果就会分配给 result 变量。下划线 (_) 表示默认可选情况,类似于传统开关语句中的 default 关键字。

switch 表达式支持多种模式,包括常量模式、类型模式、类型模式、关系模式等,是处理复杂情况的通用工具。在处理枚举时,它尤其有用,可以避免使用重复的 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"
'	};
VB   C#

在这种情况下,初始输入值、形状 变量会被分解成不同的组成部分 (圆形或矩形),并根据类型和值生成相应的信息。

4.开关表达式与开关语句

虽然开关表达式与传统的开关式语义模式有相似之处,但它有几个优点。switch 关键字表达式更加简洁,不需要break-case语句,减少了模板代码。它还允许在表达式中直接赋值,使代码更具表现力。

另一个值得注意的功能是,可以在 lambda 表达式中使用开关表达式中的表达式,也可以在方法或属性中将表达式作为表达式成员的一部分使用,从而使编程风格更加函数化。

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

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 进行分类。

切换表达式采用递归模式,根据特定页数范围将文档分为不同类型,如 "单页文档"、"小文档 "或 "大文档"。分类后的文档随后会保存到名为 "document_output.pdf "的文件中,控制台消息会告知 PDF 创建成功及其分类结果。

这种简洁、动态的方法展示了开关表达式在有效处理不同场景方面的多功能性,提供了一种根据文档属性对文档进行分类的简化方法。

6.1.输出控制台

C# 开关表达式(开发人员如何使用) 图 1

7.结论

C# switch 表达式是 C# 8.0 中引入的,它是 C# 语言的一个重要演变,已成为开发人员简化条件逻辑和增强代码表现力的一个引人注目的工具。

本手册全面探讨了它的语法、应用和优势,通过使用各种位置模式和关键字(如 "switch "和 "case")的示例,展示了它的多功能性。从直观的语法和基本用法到高级声明模式和解构功能,switch 表达式在编写简洁、可读性强的代码方面已被证明是无价之宝。

与传统的 switch 语句相比,switch 表达式更加简洁,并支持表达式结构,包括 lambda 表达式和表达式成员。开关表达式能与外部库无缝集成,并有助于简化 PDF 生成,这进一步强调了它在推进现代 C# 开发实践中的作用。

随着 C# 的不断发展,switch 表达式证明了该语言致力于为开发人员提供有效解决问题的高效、表现力强的工具。

< 前一页
C# 数学(它对开发人员的工作原理)
下一步 >
NUnit或xUnit .NET Core(开发人员如何使用)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >