跳過到頁腳內容
.NET幫助

C# 擴展方法(開發者的工作原理)

擴展方法是 C# 中的一個強大功能,允許您在不修改其源代碼的情況下向現有類型添加新功能。 它們在使代碼更易讀和易於維護方面非常有用。 在本指南中,我們將探索擴展方法的基礎知識以及如何實現它們。

什麼是擴展方法?

擴展方法是可以像現有類型的實例方法一樣被調用的特殊靜態方法。 它們是一種在不更改原始源代碼或從類繼承的情況下向現有類添加新方法的便捷方式。

要創建擴展方法,需要在一個靜態類中定義一個靜態方法。 方法的第一個參數應該是您想要擴展的類型,前面加上 this 關鍵字。 這個特殊的關鍵字告訴 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

在本節中,我們將介紹 IronPDF,我們領先行業的用於在 C# 中生成和處理 PDF 文件的庫。 我們還將看到如何利用擴展方法來創建更無縫且直觀的使用體驗。

IronPDF 以保留內容在 Web 瀏覽器中顯示的佈局和樣式的方式將 HTML 轉換為 PDF。 該庫可以使用來自文件、網址和字符串的原始 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 嗎? 您可以從我們的IronPDF 30天免費試用版開始。 它的開發用途完全免費,因此您可以真正看到它的作用。 如果您喜歡所見,IronPDF 的起價低至 liteLicense,請參閱 IronPDF 許可詳情。 為了獲得更大的折扣,請查看 Iron Software 套件的購買選項,您可以以兩種工具的價格獲得所有九種 Iron Software 工具。 祝您編程愉快!

Csharp Extension Methods 1 related to 結論

常見問題解答

什麼是 C# 擴充方法以及它們有什麼作用?

C# 擴充方法是靜態方法,允許開發人員在不更改其源代碼的情況下,向現有類型新增功能。它們使代碼更加可讀和可維護,因為允許您像呼叫實例方法一樣呼叫這些方法。

如何在 C# 中創建一個擴充方法?

要創建擴充方法,請在靜態類別中定義一個靜態方法。方法的第一個參數必須是您希望擴充的類型,並在其前加上 this 關鍵字。

擴充方法可以用於在 C# 中創建 PDF 嗎?

是的,擴充方法可以簡化在 C# 中生成 PDF 的過程。例如,您可以為字符串開發一個擴充方法,使用 PDF 庫將 HTML 內容直接轉換為 PDF。

如何在 C# 中將 HTML 內容轉換為 PDF?

您可以使用 PDF 庫的方法將 HTML 字串轉換為 PDF。可以實現擴充方法來促使此過程,讓您透過簡單的函數調用將 HTML 內容轉換為 PDF。

使用 C# 擴充方法的限制是什麼?

擴充方法無法訪問它們所擴充類型的私人成員。它們也不參加繼承或多態性,並且無法覆蓋現有的實例方法。

擴充方法如何增強與 PDF 庫的工作?

擴充方法可以增強與 PDF 庫的工作方式,通過提供簡化的方法來操作庫的功能。例如,您可以創建方法來將 URL 或 HTML 內容直接轉換為 PDF,簡化編碼過程。

如何在 C# 中使用擴充方法將 URL 轉換為 PDF?

透過擴充 Uri 類並使用擴充方法,您可以使用 PDF 庫將網站 URL 轉換為 PDF 檔案。此方法可以接收 URL 並將生成的 PDF 儲存在指定的檔案路徑中。

C# 擴充方法的一些實際例子是什麼?

C# 擴充方法的一些實際例子包括為字符串新增 Reverse 方法、WordCount 方法、為整數集合新增 Median 方法,以及為 DateTime 結構新增 StartOfWeek 方法。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。