跳過到頁腳內容
.NET幫助

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);
    }
}
$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
    }
}
$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;
    }
}
$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.
$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];
        }
    }
}
$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.
$vbLabelText   $csharpLabel

日期時間擴展方法 本週開始

假設你想找出給定日期所在星期的開始日期。 您可以為 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;
    }
}
$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.
$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");
    }
}
$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");
    }
}
$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);
    }
}
$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");
$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);
    }
}
$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");
$vbLabelText   $csharpLabel

結論

瞧!我們探索了 C# 中的擴展方法概念,學習如何使用靜態方法和靜態類別來實現它們,並使用了各種類型的實際範例。此外,我們還介紹了IronPDF,一個用於在 C# 中產生和處理 PDF 文件的庫。 當你開始將擴充方法和IronPDF結合使用時,你會發現你的程式碼可以變得多麼簡潔、易讀和有效率。

準備好體驗IronPDF了嗎? 您可以先體驗IronPDF的 30 天免費試用版。 它也完全可以免費用於開發目的,因此您可以真正了解它的功能。 如果您喜歡您所看到的, 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技術的創新,同時指導下一代技術領導者。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me