跳過到頁腳內容
.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# 中延伸方法的基本原理,讓我們來看看一些實際的範例。

字串擴充方法字數

假設您想要計算一個字串的字數。 你可以為字串類別建立一個擴充方法:

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<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 擴充方法 StartOfWeek

比方說,您想要找出某個日期的一周開始時間。 您可以為 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 將 HTML 轉換為 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 的購買選項,您可以用兩個工具的價格獲得全部九個 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 方法。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我