フッターコンテンツにスキップ
.NETヘルプ

C# Extension Methods (開発者向けの仕組み)

拡張メソッドは、C# の強力な機能であり、既存の型に新しい機能を追加することができます。 コードをより読みやすく、保守しやすくするのに非常に役立ちます。 このガイドでは、拡張メソッドの基本とその実装方法について探ります。

拡張メソッドとは何ですか?

拡張メソッドは、既存の型のインスタンスメソッドのように呼び出すことができる特別な静的メソッドです。 元のソースコードを変更したり、クラスを継承したりすることなく、既存のクラスに新しいメソッドを追加する便利な方法です。

拡張メソッドを作成するには、静的クラス内に静的メソッドを定義する必要があります。 メソッドの最初のパラメータは、拡張したい型であり、this キーワードを付けて、C# コンパイラに拡張メソッドであることを示します。 この特別なキーワードが、これが拡張メソッドであることを C# コンパイラに伝えます。

C#での拡張メソッドの実装

拡張メソッドが何であるかを理解したので、実際に実装してみましょう。 逆転させたい文字列があるとしましょう。 別の関数を書く代わりに、文字列クラスの拡張メソッドを作成することができます。

まず、新しい静的クラスStringExtensionsを作成します。 クラス名は重要ではありませんが、拡張する型の後に「Extensions」を付けるのが一般的です。 このクラス内で、Reverseという静的メソッドを定義します:

public static class StringExtensions
{
    // This extension method reverses a given string.
    public static string Reverse(this string input)
    {
        // Convert the string to a character array.
        char[] chars = input.ToCharArray();
        // Reverse the array in place.
        Array.Reverse(chars);
        // Create a new string from the reversed character array and return it.
        return new string(chars);
    }
}
public static class StringExtensions
{
    // This extension method reverses a given string.
    public static string Reverse(this string input)
    {
        // Convert the string to a character array.
        char[] chars = input.ToCharArray();
        // Reverse the array in place.
        Array.Reverse(chars);
        // Create a new string from the reversed character array and return it.
        return new string(chars);
    }
}
Public Module StringExtensions
	' This extension method reverses a given string.
	<System.Runtime.CompilerServices.Extension> _
	Public Function Reverse(ByVal input As String) As String
		' Convert the string to a character array.
		Dim chars() As Char = input.ToCharArray()
		' Reverse the array in place.
		Array.Reverse(chars)
		' Create a new string from the reversed character array and return it.
		Return New String(chars)
	End Function
End Module
$vbLabelText   $csharpLabel

この例では、Reverseという単一のパラメータを持つ公共の静的文字列メソッドを作成しました。 文字列型の前のthisキーワードは、これが文字列クラスの拡張メソッドであることを示しています。

次に、この新しい拡張メソッドをProgramクラスでどのように使用するかを見てみましょう:

class Program
{
    static void Main(string[] args)
    {
        string example = "Hello, World!";
        // Call the extension method as if it were an instance method.
        string reversed = example.Reverse();
        Console.WriteLine(reversed); // Output: !dlroW ,olleH
    }
}
class Program
{
    static void Main(string[] args)
    {
        string example = "Hello, World!";
        // Call the extension method as if it were an instance method.
        string reversed = example.Reverse();
        Console.WriteLine(reversed); // Output: !dlroW ,olleH
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim example As String = "Hello, World!"
		' Call the extension method as if it were an instance method.
		Dim reversed As String = example.Reverse()
		Console.WriteLine(reversed) ' Output: !dlroW ,olleH
	End Sub
End Class
$vbLabelText   $csharpLabel

StringExtensionsクラスのインスタンスを作成する必要がなかったことに注意してください。 代わりに、インスタンスメソッドのように文字列インスタンスで直接Reverseメソッドを使用しました。

拡張メソッドの構文

拡張メソッドはインスタンスメソッドのように見え、動作しますが、いくつかの重要な違いがあります:

  • 拡張メソッドは、拡張された型のプライベートメンバーにアクセスすることはできません。
  • また、継承や多態性には参加しません。
  • 既存のメソッドを拡張メソッドでオーバーライドすることはできません。

拡張された型が拡張メソッドと同じ署名のメソッドを持っている場合、インスタンスメソッドが常に優先されます。 拡張メソッドは、一致するインスタンスメソッドがない場合にのみ呼び出されます。

拡張メソッドの現実的な例

C#の拡張メソッドの基本を理解したので、いくつかの現実的な例を見てみましょう。

文字列拡張メソッドの単語カウント

文字列内の単語の数を数えたいとしましょう。 文字列クラスに対してWordCountという拡張メソッドを作成できます。

public static class StringExtensions
{
    // This extension method counts the number of words in a string.
    public static int WordCount(this string input)
    {
        // Split the string by whitespace characters and return the length of the resulting array.
        return input.Split(new[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Length;
    }
}
public static class StringExtensions
{
    // This extension method counts the number of words in a string.
    public static int WordCount(this string input)
    {
        // Split the string by whitespace characters and return the length of the resulting array.
        return input.Split(new[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Length;
    }
}
Imports Microsoft.VisualBasic

Public Module StringExtensions
	' This extension method counts the number of words in a string.
	<System.Runtime.CompilerServices.Extension> _
	Public Function WordCount(ByVal input As String) As Integer
		' Split the string by whitespace characters and return the length of the resulting array.
		Return input.Split( { " "c, ControlChars.Tab, ControlChars.Cr, ControlChars.Lf }, StringSplitOptions.RemoveEmptyEntries).Length
	End Function
End Module
$vbLabelText   $csharpLabel

これで、文字列内の単語の数を簡単にカウントできます:

string text = "Extension methods are awesome!";
int wordCount = text.WordCount();
Console.WriteLine($"The text has {wordCount} words."); // Output: The text has 4 words.
string text = "Extension methods are awesome!";
int wordCount = text.WordCount();
Console.WriteLine($"The text has {wordCount} words."); // Output: The text has 4 words.
Dim text As String = "Extension methods are awesome!"
Dim wordCount As Integer = text.WordCount()
Console.WriteLine($"The text has {wordCount} words.") ' Output: The text has 4 words.
$vbLabelText   $csharpLabel

IEnumerableの拡張メソッドの中央値

数字のコレクションがあり、その中央値を計算したいとしましょう。 IEnumerable<int>の拡張メソッドを作成できます:

using System;
using System.Collections.Generic;
using System.Linq;

public static class EnumerableExtensions
{
    // This extension method calculates the median of a collection of integers.
    public static double Median(this IEnumerable<int> source)
    {
        // Sort the collection and convert it to an array.
        int[] sorted = source.OrderBy(x => x).ToArray();
        int count = sorted.Length;

        if (count == 0)
        {
            throw new InvalidOperationException("The collection is empty.");
        }

        // If the count is even, return the average of the two middle elements.
        if (count % 2 == 0)
        {
            return (sorted[count / 2 - 1] + sorted[count / 2]) / 2.0;
        }
        else
        {
            // Otherwise, return the middle element.
            return sorted[count / 2];
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;

public static class EnumerableExtensions
{
    // This extension method calculates the median of a collection of integers.
    public static double Median(this IEnumerable<int> source)
    {
        // Sort the collection and convert it to an array.
        int[] sorted = source.OrderBy(x => x).ToArray();
        int count = sorted.Length;

        if (count == 0)
        {
            throw new InvalidOperationException("The collection is empty.");
        }

        // If the count is even, return the average of the two middle elements.
        if (count % 2 == 0)
        {
            return (sorted[count / 2 - 1] + sorted[count / 2]) / 2.0;
        }
        else
        {
            // Otherwise, return the middle element.
            return sorted[count / 2];
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Linq

Public Module EnumerableExtensions
	' This extension method calculates the median of a collection of integers.
	<System.Runtime.CompilerServices.Extension> _
	Public Function Median(ByVal source As IEnumerable(Of Integer)) As Double
		' Sort the collection and convert it to an array.
		Dim sorted() As Integer = source.OrderBy(Function(x) x).ToArray()
		Dim count As Integer = sorted.Length

		If count = 0 Then
			Throw New InvalidOperationException("The collection is empty.")
		End If

		' If the count is even, return the average of the two middle elements.
		If count Mod 2 = 0 Then
			Return (sorted(count \ 2 - 1) + sorted(count \ 2)) / 2.0
		Else
			' Otherwise, return the middle element.
			Return sorted(count \ 2)
		End If
	End Function
End Module
$vbLabelText   $csharpLabel

この拡張メソッドを使って、コレクションの中央値を簡単に見つけることができます:

int[] numbers = { 5, 3, 9, 1, 4 };
double median = numbers.Median();
Console.WriteLine($"The median value is {median}."); // Output: The median value is 4.
int[] numbers = { 5, 3, 9, 1, 4 };
double median = numbers.Median();
Console.WriteLine($"The median value is {median}."); // Output: The median value is 4.
Dim numbers() As Integer = { 5, 3, 9, 1, 4 }
Dim median As Double = numbers.Median()
Console.WriteLine($"The median value is {median}.") ' Output: The median value is 4.
$vbLabelText   $csharpLabel

DateTimeの拡張メソッドの週の開始日

特定の日付の週の開始日を見つけたいとしましょう。 DateTime構造体に対する拡張メソッドを作成できます:

public static class DateTimeExtensions
{
    // This extension method calculates the start of the week for a given date.
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek = DayOfWeek.Monday)
    {
        // Calculate the difference in days between the current day and the start of the week.
        int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
        // Subtract the difference to get the start of the week.
        return dt.AddDays(-1 * diff).Date;
    }
}
public static class DateTimeExtensions
{
    // This extension method calculates the start of the week for a given date.
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek = DayOfWeek.Monday)
    {
        // Calculate the difference in days between the current day and the start of the week.
        int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
        // Subtract the difference to get the start of the week.
        return dt.AddDays(-1 * diff).Date;
    }
}
Public Module DateTimeExtensions
	' This extension method calculates the start of the week for a given date.
'INSTANT VB NOTE: The parameter startOfWeek was renamed since Visual Basic will not allow parameters with the same name as their enclosing function or property:
	<System.Runtime.CompilerServices.Extension> _
	Public Function StartOfWeek(ByVal dt As DateTime, Optional ByVal startOfWeek_Conflict As DayOfWeek = DayOfWeek.Monday) As DateTime
		' Calculate the difference in days between the current day and the start of the week.
		Dim diff As Integer = (7 + (dt.DayOfWeek - startOfWeek_Conflict)) Mod 7
		' Subtract the difference to get the start of the week.
		Return dt.AddDays(-1 * diff).Date
	End Function
End Module
$vbLabelText   $csharpLabel

これで、任意の日付の週の開始日を簡単に見つけることができます:

DateTime today = DateTime.Today;
DateTime startOfWeek = today.StartOfWeek();
Console.WriteLine($"The start of the week is {startOfWeek.ToShortDateString()}.");
// Output will depend on the current date, e.g. The start of the week is 17/06/2024.
DateTime today = DateTime.Today;
DateTime startOfWeek = today.StartOfWeek();
Console.WriteLine($"The start of the week is {startOfWeek.ToShortDateString()}.");
// Output will depend on the current date, e.g. The start of the week is 17/06/2024.
Dim today As DateTime = DateTime.Today
Dim startOfWeek As DateTime = today.StartOfWeek()
Console.WriteLine($"The start of the week is {startOfWeek.ToShortDateString()}.")
' Output will depend on the current date, e.g. The start of the week is 17/06/2024.
$vbLabelText   $csharpLabel

IronPDFを使ったPDF生成と拡張メソッド

このセクションでは、C#でPDFファイルを生成し作業するための業界をリードするライブラリであるIronPDFを紹介します。 また、このライブラリをよりシームレスで直感的に操作するための拡張メソッドを利用する方法も見ていきます。

IronPDFは、HTMLをWebブラウザで表示されるようにレイアウトとスタイルを維持しながらPDFに変換します。 ライブラリは、ファイル、URL、文字列からの生のHTMLと一緒に作業することができます。 簡単な概要はこちらです:

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

シンプルなPDFの作成

拡張メソッドの話に入る前に、IronPDFを使ってHTMLからシンプルなPDFを作成する方法を見てみましょう:

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        var PDF = renderer.RenderHtmlAsPdf("Hello, World!");
        PDF.SaveAs("HelloWorld.PDF");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        var PDF = renderer.RenderHtmlAsPdf("Hello, World!");
        PDF.SaveAs("HelloWorld.PDF");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()
		Dim PDF = renderer.RenderHtmlAsPdf("Hello, World!")
		PDF.SaveAs("HelloWorld.PDF")
	End Sub
End Class
$vbLabelText   $csharpLabel

このコードスニペットは、「Hello, World!」というテキストのPDFを作成し、「HelloWorld.PDF」という名前でファイルに保存します。

IronPDFの拡張メソッド

IronPDFの機能を強化し、作業を容易にするために拡張メソッドをどのように使用できるかを見ていきましょう。 例えば、文字列クラスのインスタンスを受け取り、そこから直接PDFを生成する拡張メソッドを作成することができます。

using IronPdf;

public static class StringExtensions
{
    // This extension method converts a string containing HTML to a PDF and saves it.
    public static void SaveAsPdf(this string htmlContent, string filePath)
    {
        var renderer = new ChromePdfRenderer();
        var PDF = renderer.RenderHtmlAsPdf(htmlContent);
        PDF.SaveAs(filePath);
    }
}
using IronPdf;

public static class StringExtensions
{
    // This extension method converts a string containing HTML to a PDF and saves it.
    public static void SaveAsPdf(this string htmlContent, string filePath)
    {
        var renderer = new ChromePdfRenderer();
        var PDF = renderer.RenderHtmlAsPdf(htmlContent);
        PDF.SaveAs(filePath);
    }
}
Imports IronPdf

Public Module StringExtensions
	' This extension method converts a string containing HTML to a PDF and saves it.
	<System.Runtime.CompilerServices.Extension> _
	Public Sub SaveAsPdf(ByVal htmlContent As String, ByVal filePath As String)
		Dim renderer = New ChromePdfRenderer()
		Dim PDF = renderer.RenderHtmlAsPdf(htmlContent)
		PDF.SaveAs(filePath)
	End Sub
End Module
$vbLabelText   $csharpLabel

この拡張メソッドを使用すれば、文字列から直接PDFを生成することができます:

string html = "<h1>Extension Methods and IronPDF</h1><p>Generating PDFs has never been easier!</p>";
html.SaveAsPdf("ExtensionMethodsAndIronPDF.PDF");
string html = "<h1>Extension Methods and IronPDF</h1><p>Generating PDFs has never been easier!</p>";
html.SaveAsPdf("ExtensionMethodsAndIronPDF.PDF");
Dim html As String = "<h1>Extension Methods and IronPDF</h1><p>Generating PDFs has never been easier!</p>"
html.SaveAsPdf("ExtensionMethodsAndIronPDF.PDF")
$vbLabelText   $csharpLabel

URLからのPDF生成

もう一つ便利な拡張メソッドを作成できるのは、URLからPDFを生成するものです。 Uriクラスを拡張してこれを実現します:

using IronPdf;

public static class UriExtensions
{
    // This extension method converts a web URL to a PDF and saves it.
    public static void SaveAsPdf(this Uri url, string filePath)
    {
        var renderer = new ChromePdfRenderer();
        var PDF = renderer.RenderUrlAsPdf(url.AbsoluteUri);
        PDF.SaveAs(filePath);
    }
}
using IronPdf;

public static class UriExtensions
{
    // This extension method converts a web URL to a PDF and saves it.
    public static void SaveAsPdf(this Uri url, string filePath)
    {
        var renderer = new ChromePdfRenderer();
        var PDF = renderer.RenderUrlAsPdf(url.AbsoluteUri);
        PDF.SaveAs(filePath);
    }
}
Imports IronPdf

Public Module UriExtensions
	' This extension method converts a web URL to a PDF and saves it.
	<System.Runtime.CompilerServices.Extension> _
	Public Sub SaveAsPdf(ByVal url As Uri, ByVal filePath As String)
		Dim renderer = New ChromePdfRenderer()
		Dim PDF = renderer.RenderUrlAsPdf(url.AbsoluteUri)
		PDF.SaveAs(filePath)
	End Sub
End Module
$vbLabelText   $csharpLabel

これで、URLから簡単にPDFを生成できます:

Uri url = new Uri("https://www.ironpdf.com/");
url.SaveAsPdf("UrlToPdf.PDF");
Uri url = new Uri("https://www.ironpdf.com/");
url.SaveAsPdf("UrlToPdf.PDF");
Dim url As New Uri("https://www.ironpdf.com/")
url.SaveAsPdf("UrlToPdf.PDF")
$vbLabelText   $csharpLabel

結論

そして、C#の拡張メソッドの概念を探り、静的メソッドと静的クラスを使ってそれらを実装する方法を学びさまざまなタイプの実例を使用しました。さらに、IronPDFというC#でPDFファイルを生成し作業するためのライブラリを紹介しました。 拡張メソッドとIronPDFを一緒に使い始めると、コードがどれだけクリーンで読みやすく、効率的になるかがわかります。

IronPDFを実際に手に取る準備はできましたか? 30日間無料のトライアルをIronPDFで始められます。 開発目的であれば、完全に無料で使用できますので、その実力を十分に実感できます。 気に入ったら、IronPDFのライセンス詳細については、liteLicenseから始まります。 さらにお得を狙うなら、Iron Software Suiteの購入オプションをチェックしてください。ここでは、9つのIron Softwareツールを2つの価格で手に入れることができます。 コーディングを楽しんでください!

Csharp Extension Methods 1 related to 結論

よくある質問

C# 拡張メソッドとは何か、それらはどのように役立ちますか?

C# 拡張メソッドは、開発者が既存の型に新しい機能をソースコードを変更することなく追加できる静的メソッドです。これにより、まるで型のインスタンスメソッドであるかのようにそれらのメソッドを呼び出すことができ、コードがより読みやすく、メンテナンスしやすくなります。

C# で拡張メソッドを作成するにはどうすればいいですか?

拡張メソッドを作成するには、静的クラス内に静的メソッドを定義します。メソッドの最初のパラメータは拡張したい型であり、this キーワードを前置すべきです。

C# で拡張メソッドを使って PDF を作成できますか?

はい、拡張メソッドは C# での PDF 生成を簡略化できます。例えば、HTML コンテンツを直接 PDF に変換するための拡張メソッドを文字列に対して開発することができます。

C# で HTML コンテンツを PDF に変換するにはどうすればよいですか?

PDF ライブラリのメソッドを使用して HTML 文字列を PDF に変換できます。拡張メソッドを実装して、このプロセスを簡略化し、HTML コンテンツを単純なメソッド呼び出しで PDF に変換できるようにします。

C# で拡張メソッドを使用する際の制限は何ですか?

拡張メソッドは、拡張された型のプライベートメンバーにアクセスすることはできません。また、継承やポリモーフィズムに参加することはできず、既存のインスタンスメソッドをオーバーライドすることもできません。

拡張メソッドは、どのようにして PDF ライブラリの使用を強化できますか?

拡張メソッドは、ライブラリの機能との相互作用を簡略化する方法を提供することにより、PDF ライブラリの使用を強化できます。例えば、URLやHTMLコンテンツを直接PDFに変換する方法を作成し、コーディングプロセスを合理化できます。

C# で拡張メソッドを使用して URL を PDF に変換するにはどうすればよいですか?

Uri クラスを拡張メソッドで拡張することにより、PDF ライブラリを使用して WEB URL を PDF ファイルに変換できます。このメソッドは、URL を処理し、結果の PDF を指定されたファイルパスに保存できます。

C# の拡張メソッドの実用的な例は何ですか?

C# 拡張メソッドの実用的な例には、文字列に対して Reverse メソッドを追加すること、文字列の語数を数える WordCount メソッド、整数のコレクションに対する Median メソッド、および DateTime 構造に対する StartOfWeek メソッドがあります。

Curtis Chau
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。