跳過到頁腳內容
.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",並從中安裝。

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 的委託,其簽名與 AddPassword 方法相同。 名為 handler 的此委託實例被賦予 AddPassword 方法。 然後使用 Invoke 方法呼叫委託,傳遞 document 實例,並將傳回的密碼指派給 documentPassword 屬性。

最後,對 SaveAs 呼叫 document 方法,將其儲存為"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 提供免費試用以測試其完整功能。 它可從 $999 起獲得商業用途許可

常見問題解答

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

C# 委派是到方法的類型安全指標,允許方法作為參數傳遞並動態調用。它們對於編寫靈活、模組化和可擴展的程式碼至關重要,支援事件處理、回調和函數式程式設計範式。

如何在 C# 中使用委派生成 PDF?

委派可以增強 PDF 生成,透過啟用文件事件的回調和將動態內容注入 PDF。例如,委派可以訂閱文件事件或協助生成使用 IronPDF 的動態 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將公司轉型為服務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 小時在線上。
聊天
電子郵件
打電話給我