跳至頁尾內容
開發者更新

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

擴充方法是 C# 中一個強大的功能,允許您在不修改其源程式碼的情況下,為現有型別新增新的功能。 它們在增加程式碼可讀性和可維護性方面非常有用。 在本指南中,我們將探討擴充方法的基礎知識以及如何實現它們。

什麼是擴充方法?

擴充方法是特殊的靜態方法,可以像現有型別的實例方法一樣被調用。 它們是一種方便的方法,可以在不更改原始源程式碼或繼承該類的情況下,為現有類新增新方法。

要建立一個擴充方法,您需要在一個靜態類中定義一個靜態方法。 該方法的第一個參數應該是您想要擴充的型別,並且需要加上this關鍵字。 此特殊關鍵字告訴 C# 編譯器這是一個擴充方法。

Implementing Extension Methods in 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 將 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 了嗎? 您可以從我們的IronPDF的30天免費試用開始。 它在開發用途上是完全免費的,因此您可以真正了解它的功能。 而且,如果您喜歡您所見的,IronPDF 的價格從 liteLicense 開始,有關 IronPDF 授權的詳細資訊。 為了獲得更大的節省,請查看 Iron Software Suite 的購買選項,您可以以兩個工具的價格獲得所有九個 Iron Software 工具。 祝您編程愉快!

Csharp Extension Methods 1 related to 結論

常見問題

什麼是C#擴展方法,這些方法有什麼用處?

C#擴展方法是允許開發者在不改變原始程式碼的情況下為現有型別新增新功能的靜態方法。它們使程式碼更具可讀性和可維護性,因為您可以像調用型別的實例方法一樣調用這些方法。

您如何在C#中建立擴展方法?

要建立擴展方法,需要在靜態類中定義靜態方法。方法的第一個參數必須是您想擴展的型別,並使用this關鍵字。

擴展方法是否可以用於在C#中建立PDF?

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

如何將HTML內容轉換為C#中的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核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

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