.NET ヘルプ

C# スイッチ式(開発者向けの動作方法)

更新済み 12月 12, 2023
共有:

C#は進化を続けており、言語の表現力を高め、開発者の体験を向上させる機能が組み込まれています。 これらの特徴の中で、特筆すべきはswitch式であり、単一の式内で複数の条件を管理するための強力で簡潔なツールです。

この包括的な調査では、C#のスイッチ式の複雑さを探り、その構文、応用、および利点を強調する例を提供します。

パターンマッチングや定数から型パターン、そして「switch」や「case」といったキーワードの使用まで、この言語機能の多様な要素を探索します。 ディスカッションでは、スイッチ式の文脈内での役割を明確にするために、定数パターン、関係パターン、およびタイプパターンなどのさまざまなパターンが取り上げられています。

さらに、現実世界のシナリオにおけるスイッチ式の組み込みを検討し、その有用性を示し、構文と実装の明確化を行います。 スイッチ式の詳細な知識については、こちらを訪れてください 記事.

この記事では、スイッチ式の例を示し、それらの使用事例をテストします。 IronPDF C# PDF ライブラリ。

スイッチ式の導入

switch式は、C# 8.0で導入され、開発者が条件ロジックを扱う方法においてパラダイムシフトを表します。 従来、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キーワードに似ています。

スイッチ式は、定数パターン、タイプパターン、タイプパターン、関係パターンなど、幅広いパターンに対応しており、複雑なシナリオを処理するための多用途なツールです。 列挙型を扱う際に特に役立ち、反復的なcase文の必要性を避けることができます。

高度なパターンと分解

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 変数がそのコンポーネントに分解されます。 (円、または長方形)、適切なメッセージはタイプと値に基づいて生成されます。

スイッチ式スイッチ文 の違い

スイッチ式は従来のスイッチに似たセマンティクスパターンと共通点がありますが、いくつかの利点を提供します。 スイッチキーワード式はより簡潔であり、break-case ステートメントの必要性を排除し、ボイラープレートコードを減らします。 それにより、式の中で直接値を割り当てることができ、コードがより表現力豊かになります。

もう一つの注目すべき機能は、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#

実際のアプリケーションにおける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式を使用して分類されます。

スイッチ式は再帰パターンを使用して、特定のページ数範囲に応じて「シングルページドキュメント」、「小型ドキュメント」、または「大型ドキュメント」などの異なるタイプに文書を分類します。 機密文書は「document_output.pdf」という名前のファイルに保存され、その分類結果とともに、PDFの作成が成功した旨を知らせるコンソールメッセージが表示されます。

この簡潔で動的なアプローチは、スイッチ式の表現が異なるシナリオを効率的に処理する多用途性を示し、文書をその特性に基づいて分類するスリム化された方法を提供します。

6.1. 出力コンソール

C# のスイッチ式(開発者向けの仕組み)図1

7. 結論

C#スイッチ式は、C# 8.0で導入され、言語の重要な進化として登場し、開発者が条件ロジックを簡素化し、コードの表現力を向上させるための魅力的なツールとなっています。

この包括的な探求では、構文、用途、および利点に触れ、「switch」や「case」などのキーワードを使用して、さまざまな位置パターンを利用した例を通じてその多様性を示してきました。直感的な構文と基本的な使用法から、高度な宣言パターンおよび分解能力まで、switch式はクリーンで読みやすいコードを作成するうえで非常に貴重であることが証明されました。

従来のswitch文との比較では、それが簡潔であることや、ラムダ式や表現形式のメンバーを含む表現力豊かな構造をサポートしていることが強調されています。 外部ライブラリとシームレスに統合し、PDF生成を効率化することができる能力は、スイッチ式が現代のC#開発慣行を前進させる上での役割をさらに強調しています。

C#が進化し続ける中、switch式は、効果的な問題解決のために開発者に効率的で表現力のあるツールを提供するという言語のコミットメントを実証するものです。

< 以前
C# 数学(開発者向けの使い方)
次へ >
NUnitまたはxUnit .NET Core(開発者への動作方法)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >