跳過到頁腳內容
.NET幫助

C# 委託(對於開發者的運行原理)

在 C# 程式設計中,了解委託對於撰寫彈性和可擴充的程式碼是最重要的。 委託是一種功能強大的實體,有助於在語言中實現回呼、事件處理和函式編程範例。 Microsoft有關 Delegates 的指南提供了有關在 C# 應用程式中使用的 Delegate 實例的全面概述。

在這份全面的指南中,我們將深入探討 C# delegates 的複雜性,探索它們的功能、使用案例,以及它們如何賦予開發人員撰寫更多模組化與可擴充程式碼的能力。

瞭解 C# 委託:回調的骨幹。

就其核心而言,C# 中的 delegate 是一種類型安全的物件,也稱為函數指標,可封裝一個或多個方法。 委託能夠建立函式的參照,提供一種方法來傳遞方法作為參數、將其儲存在資料結構中,並動態地呼叫它們。 這使得委託成為實現回呼機制和執行事件驅動架構的基石。

C# 委託的主要特徵

1.類型安全:委託是類型安全的,可確保其引用的方法簽章與委託簽章一致。 2.多播:委託支援多播調用,允許將多個方法合併為單一委託實體。 當被呼叫時,多點傳送委託中的所有方法都會依序被呼叫。 3.Anonymous Methods and Lambda Expressions: C# delegates 可與匿名方法和 lambda 表達式無縫整合,提供簡潔的語法來定義內嵌的方法體。

基本用法和語法

使用委託的基本步驟包括使用委託類型和參數進行宣告、實體化,以及透過定義回撥方法進行調用。 以下是一個基本範例:

// Delegate declaration
public delegate void MyDelegate(string message);

class Program
{
    static void Main(string[] args)
    {
        // Instantiation
        MyDelegate myDelegate = DisplayMessage;

        // Invocation
        myDelegate("Hello, Delegates!");
    }

    // Method to be referenced
    static void DisplayMessage(string message)
    {
        Console.WriteLine(message);
    }
}
// Delegate declaration
public delegate void MyDelegate(string message);

class Program
{
    static void Main(string[] args)
    {
        // Instantiation
        MyDelegate myDelegate = DisplayMessage;

        // Invocation
        myDelegate("Hello, Delegates!");
    }

    // Method to be referenced
    static void DisplayMessage(string message)
    {
        Console.WriteLine(message);
    }
}
' Delegate declaration
Public Delegate Sub MyDelegate(ByVal message As String)

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Instantiation
		Dim myDelegate As MyDelegate = AddressOf DisplayMessage

		' Invocation
		myDelegate("Hello, Delegates!")
	End Sub

	' Method to be referenced
	Private Shared Sub DisplayMessage(ByVal message As String)
		Console.WriteLine(message)
	End Sub
End Class
$vbLabelText   $csharpLabel

Callback Scenarios:利用委託實現彈性。

委託的主要用途之一是執行回呼。 考量方法需要在特定事件發生時通知外部元件的情境。 代表提供簡潔且模組化的解決方案:

using System;

class Program
{
    static void Main(string[] args)
    {
        EventPublisher publisher = new EventPublisher();
        EventSubscriber subscriber = new EventSubscriber(publisher);

        publisher.SimulateEvent("Test Event");
    }
}

public class EventPublisher
{
    // Declare a delegate type
    public delegate void EventHandler(string eventName);

    // Create an instance of the delegate
    public event EventHandler EventOccurred;

    // Simulate an event
    public void SimulateEvent(string eventName)
    {
        // Invoke the delegate to notify subscribers
        EventOccurred?.Invoke(eventName);
    }
}

public class EventSubscriber
{
    public EventSubscriber(EventPublisher eventPublisher)
    {
        // Subscribe to the event using the delegate
        eventPublisher.EventOccurred += HandleEvent;
    }

    // Method to be invoked when the event occurs
    private void HandleEvent(string eventName)
    {
        Console.WriteLine($"Event handled: {eventName}");
    }
}
using System;

class Program
{
    static void Main(string[] args)
    {
        EventPublisher publisher = new EventPublisher();
        EventSubscriber subscriber = new EventSubscriber(publisher);

        publisher.SimulateEvent("Test Event");
    }
}

public class EventPublisher
{
    // Declare a delegate type
    public delegate void EventHandler(string eventName);

    // Create an instance of the delegate
    public event EventHandler EventOccurred;

    // Simulate an event
    public void SimulateEvent(string eventName)
    {
        // Invoke the delegate to notify subscribers
        EventOccurred?.Invoke(eventName);
    }
}

public class EventSubscriber
{
    public EventSubscriber(EventPublisher eventPublisher)
    {
        // Subscribe to the event using the delegate
        eventPublisher.EventOccurred += HandleEvent;
    }

    // Method to be invoked when the event occurs
    private void HandleEvent(string eventName)
    {
        Console.WriteLine($"Event handled: {eventName}");
    }
}
Imports System

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim publisher As New EventPublisher()
		Dim subscriber As New EventSubscriber(publisher)

		publisher.SimulateEvent("Test Event")
	End Sub
End Class

Public Class EventPublisher
	' Declare a delegate type
	Public Delegate Sub EventHandler(ByVal eventName As String)

	' Create an instance of the delegate
	Public Event EventOccurred As EventHandler

	' Simulate an event
	Public Sub SimulateEvent(ByVal eventName As String)
		' Invoke the delegate to notify subscribers
		RaiseEvent EventOccurred(eventName)
	End Sub
End Class

Public Class EventSubscriber
	Public Sub New(ByVal eventPublisher As EventPublisher)
		' Subscribe to the event using the delegate
		AddHandler eventPublisher.EventOccurred, AddressOf HandleEvent
	End Sub

	' Method to be invoked when the event occurs
	Private Sub HandleEvent(ByVal eventName As String)
		Console.WriteLine($"Event handled: {eventName}")
	End Sub
End Class
$vbLabelText   $csharpLabel

使用委託進行函式程式設計。

代表在 C# 中接受函式程式設計概念的過程中扮演關鍵的角色。 使用具有高階函數的委託,開發人員可以傳遞函數作為參數、回傳函數,並建立更具表現力、更簡潔的程式碼:

public delegate int MyDelegate(int x, int y);

public class Calculator
{
    public int PerformOperation(MyDelegate operation, int operand1, int operand2)
    {
        // Execute the operation method reference through the passed delegate
        return operation(operand1, operand2);
    }
}

// Usage
var calculator = new Calculator();
int result = calculator.PerformOperation((x, y) => x + y, 5, 3); // Adds 5 and 3
Console.WriteLine(result); // Outputs: 8
public delegate int MyDelegate(int x, int y);

public class Calculator
{
    public int PerformOperation(MyDelegate operation, int operand1, int operand2)
    {
        // Execute the operation method reference through the passed delegate
        return operation(operand1, operand2);
    }
}

// Usage
var calculator = new Calculator();
int result = calculator.PerformOperation((x, y) => x + y, 5, 3); // Adds 5 and 3
Console.WriteLine(result); // Outputs: 8
Public Delegate Function MyDelegate(ByVal x As Integer, ByVal y As Integer) As Integer

Public Class Calculator
	Public Function PerformOperation(ByVal operation As MyDelegate, ByVal operand1 As Integer, ByVal operand2 As Integer) As Integer
		' Execute the operation method reference through the passed delegate
		Return operation(operand1, operand2)
	End Function
End Class

' Usage
Private calculator = New Calculator()
Private result As Integer = calculator.PerformOperation(Function(x, y) x + y, 5, 3) ' Adds 5 and 3
Console.WriteLine(result) ' Outputs: 8
$vbLabelText   $csharpLabel

介紹 IronPDF:簡要概述

C# Delegates (How It Works For Developers):圖 1 - IronPdf 網頁

進一步瞭解 IronPDF 的功能,IronPDF 是一個功能豐富的函式庫,旨在促進 C# 應用程式中 PDF 的產生、操作和互動。 無論您是需要從頭開始建立 PDF、將 HTML 轉換成 PDF,或是從現有的 PDF 中抽取內容,IronPDF 都能提供一套完整的工具來簡化這些工作。 其多功能性使其成為從事各種專案的開發人員的寶貴資產。

安裝 IronPdf:快速入門

要開始在您的 C# 專案中利用 IronPDF 函式庫,您可以輕鬆安裝 IronPDF NuGet 套件。 在套件管理員控制台中使用下列指令:

Install-Package IronPdf

另外,您也可以在 NuGet 套件管理員中搜尋"IronPDF",並從中安裝。

!a href="/static-assets/pdf/blog/csharp-delegates-guide/csharp-delegates-guide-2.webp">C# Delegates (How It Works For Developers):圖 2 - 透過 NuGet 套件管理員安裝 IronPDF 函式庫。

Delegates in C#:快速回顧

在 C# 中,委託作為類型安全的函數指標,允許方法被引用並作為參數傳遞。 如上所述,代表在不同的情境中扮演著關鍵的角色。 現在,問題出現了:C# delegates 如何融入 IronPDF 的環境,它們是否能有效地配合使用?

委託與 IronPDF 的整合。

1.使用回呼方法處理文件事件。

利用 IronPDF 代表的一種方式是透過回呼文件事件。 IronPdf 提供了您可以使用委託函訂閱的事件,讓您可以在文件產生過程中的特定點執行自訂邏輯。 舉例來說

using IronPdf;

public delegate string AddPasswordEventHandler(PdfDocument e);

string AddPassword(PdfDocument document)
{
    string password = "";
    if (document.Password == "")
    {
        password = "Iron123";
    }
    return password;
}

PdfDocument document = new PdfDocument("StyledDocument.pdf");
AddPasswordEventHandler handler = AddPassword;
document.Password = handler.Invoke(document); // Subscribe to the event
document.SaveAs("PasswordProtected.pdf");
using IronPdf;

public delegate string AddPasswordEventHandler(PdfDocument e);

string AddPassword(PdfDocument document)
{
    string password = "";
    if (document.Password == "")
    {
        password = "Iron123";
    }
    return password;
}

PdfDocument document = new PdfDocument("StyledDocument.pdf");
AddPasswordEventHandler handler = AddPassword;
document.Password = handler.Invoke(document); // Subscribe to the event
document.SaveAs("PasswordProtected.pdf");
Imports IronPdf

Public Delegate Function AddPasswordEventHandler(ByVal e As PdfDocument) As String

Private Function AddPassword(ByVal document As PdfDocument) As String
	Dim password As String = ""
	If document.Password = "" Then
		password = "Iron123"
	End If
	Return password
End Function

Private document As New PdfDocument("StyledDocument.pdf")
Private handler As AddPasswordEventHandler = AddressOf AddPassword
document.Password = handler.Invoke(document) ' Subscribe to the event
document.SaveAs("PasswordProtected.pdf")
$vbLabelText   $csharpLabel

在此 C# 程式碼片段中,定義了一個名為 AddPassword 的方法,以接受一個 PdfDocument 作為參數,並傳回一個字串。 在此方法中,一個名為 password 的字串變數會被初始化,並且會對所提供 PdfDocumentPassword 屬性執行條件檢查。 如果密碼是空字串,則將值"Iron123"賦予 password 變數,並傳回該變數。

接下來,會建立一個檔案名稱為 "StyledDocument.pdf" 的 PdfDocument 範例。 一個名為 AddPasswordEventHandler 的 delegate 已宣告,其簽章與 AddPassword 方法相同。 命名為 handler 的此 delegate 的實體被指派給 AddPassword 方法。 然後使用 Invoke 方法來呼叫該 delegate,並傳入 document 的實體,然後將傳回的密碼指定給 documentPassword 屬性。

最後,在 document 上呼叫 SaveAs 方法,將其儲存為 "PasswordProtected.pdf"。 該代碼有效地使用一個委派,根據 AddPassword 方法中的特定條件,動態地確定和設定 PdfDocument 的密碼。

2.使用委託實現動態內容

也可以使用委託將動態內容注入 PDF 文件中。 IronPDF 支援插入 HTML 內容來 從 HTML 產生 PDF,開發人員可以使用委託來根據特定條件或資料動態產生 HTML:

// Assuming GetDynamicContent is a delegate that generates dynamic HTML content
Func<string> getDynamicContent = () =>
{
    // Custom logic to generate dynamic content
    return "<p>This is dynamic content based on some condition.</p>";
};

// Incorporate dynamic HTML into the PDF
var pdfRenderer = new ChromePdfRenderer();
var pdfDocument = pdfRenderer.RenderHtmlAsPdf($"<html><body>{getDynamicContent()}</body></html>");
pdfDocument.SaveAs("DynamicContentDocument.pdf");
// Assuming GetDynamicContent is a delegate that generates dynamic HTML content
Func<string> getDynamicContent = () =>
{
    // Custom logic to generate dynamic content
    return "<p>This is dynamic content based on some condition.</p>";
};

// Incorporate dynamic HTML into the PDF
var pdfRenderer = new ChromePdfRenderer();
var pdfDocument = pdfRenderer.RenderHtmlAsPdf($"<html><body>{getDynamicContent()}</body></html>");
pdfDocument.SaveAs("DynamicContentDocument.pdf");
' Assuming GetDynamicContent is a delegate that generates dynamic HTML content
Dim getDynamicContent As Func(Of String) = Function()
	' Custom logic to generate dynamic content
	Return "<p>This is dynamic content based on some condition.</p>"
End Function

' Incorporate dynamic HTML into the PDF
Dim pdfRenderer = New ChromePdfRenderer()
Dim pdfDocument = pdfRenderer.RenderHtmlAsPdf($"<html><body>{getDynamicContent()}</body></html>")
pdfDocument.SaveAs("DynamicContentDocument.pdf")
$vbLabelText   $csharpLabel

在這個範例中,getDynamicContent 代表動態產生 HTML 內容,然後將其嵌入 PDF 文件中。

C# Delegates (How It Works For Developers):圖 3 - 從之前的程式碼輸出 PDF

若要高效地使用 IronPdf,請造訪 IronPDF說明文件

結論

總而言之,C# 委託是程式碼靈活性和模組化的基石。 這些工具可讓開發人員實現回呼、處理事件,並接受功能性程式設計範例,例如以程式化方式變更方法呼叫的能力。 作為 C# 工具包中的多用途工具,委託可賦予開發人員創造更具可維護性、可擴展性和表現力代碼的能力。 無論您是要建立事件驅動的應用程式、實作回呼機制,或是探索函式程式設計,C# 代表都是您在程式設計之旅中的強大盟友。

C# delegates 與 IronPDF 可以組成合作的二人組,增強應用程式中的文件生成能力。 無論您是自訂文件事件或注入動態內容,委託都能提供靈活的機制來擴充 IronPDF 的功能。 在探索各種可能性的同時,請考慮您專案的具體需求,以及代表如何透過 IronPDF 促成更量身打造、更動態的 PDF 生成流程。

IronPdf 提供免費試用以測試其完整功能。 它可以從$799開始授權給商業使用

常見問題解答

什麼是 C# 委託,為什麼它們很重要?

C# delegates 是指向方法的類型安全指針,允許方法作為參數傳遞並動態調用。它們對於撰寫彈性、模組化及可擴充的程式碼至關重要,並可支援事件處理、回撥及功能性程式設計範例。

如何在 C# 中使用委託製作 PDF?

透過啟用文件事件的回呼以及在 PDF 中注入動態內容,可以利用委託來增強 PDF 的產生。例如,委託可以訂閱文件事件,或使用 IronPDF 促成 PDF 中動態 HTML 內容的產生。

在 C# 的事件驅動程式設計中,委託的角色是什麼?

在事件驅動程式設計中,委託允許建立可以回應特定事件的事件處理器,從而實現簡潔且模組化的回呼機制,在事件發生時通知外部元件。

C# 中的多播委託如何運作?

C# 中的多播委託允許將多個方法合併為單一委託實體。這可依序調用委託中的所有方法,方便複雜的事件處理情境。

C# 委託可以使用 lambda 表達式嗎?

是的,C# 委託可以與 lambda 表達式一起使用,提供簡潔的方式來定義內嵌的方法體。這可增強程式碼的可讀性和彈性,讓您輕鬆地將方法指派給委託。

如何在 C# 中宣告和使用委託?

若要在 C# 中使用委託,請宣告委託類型、以方法參照實體化它,然後調用它來執行參照的方法。這個過程可以靈活地調用方法和動態執行程式碼。

開發人員如何將 PDF 函式庫整合到他們的 C# 專案中製作文件?

開發人員可透過套件管理員控制台或 NuGet 套件管理員安裝適當的 NuGet 套件,以整合 PDF 函式庫。IronPDF 等函式庫為 PDF 的產生與處理提供了強大的解決方案。

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

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

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

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。