.NET 幫助

C# 委派(開發者如何使用)

Chipego
奇佩戈·卡林达
2024年2月18日
分享:

在 C# 編程中,了解委託對於撰寫靈活且可擴展的代碼至關重要。 委派作為強大的實體,促進了語言中回調函數、事件處理和函數式編程範式的實現。 微軟有關委派的指南提供了在 C# 應用程式中使用的委派實例的全面概述。

在這份全面的指南中,我們將深入探討 C# 委派的複雜性,探索其功能、使用案例,以及它們如何使開發人員能夠編寫更加模組化和可擴展的代碼。

了解 C# 委派:回呼的支柱

在其核心,C#中的委派是類型安全的物件,也被稱為函數指標,封裝了一個方法或多個方法。 委託允許創建對函數的引用,提供了一種將方法作為參數傳遞、將它們儲存在數據結構中,並動態調用它們的方法。 這使得委託成為實現回呼機制和實現事件驅動架構的基石。

C# 委派的主要特性

  1. 型別安全:委派是型別安全的,確保它們引用的方法簽章與委派簽章一致。

  2. 多播:委派支持多播調用,允許將多個方法組合成一個委派實例。 當調用時,多播委託中的所有方法會依序被呼叫。

  3. 匿名方法和 Lambda 表達式: C# 委派可以無縫整合匿名方法和 Lambda 表達式,提供簡潔的語法來在線定義方法主體。

基本用法和語法

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

// Delegate declaration
public delegate void MyDelegate(string message);
// Instantiation
MyDelegate myDelegate = DisplayMessage;
// Method to be referenced
static void DisplayMessage(string message)
{
    Console.WriteLine(message);
}
// Invocation
myDelegate("Hello, Delegates!");
// Delegate declaration
public delegate void MyDelegate(string message);
// Instantiation
MyDelegate myDelegate = DisplayMessage;
// Method to be referenced
static void DisplayMessage(string message)
{
    Console.WriteLine(message);
}
// Invocation
myDelegate("Hello, Delegates!");
' Delegate declaration
Public Delegate Sub MyDelegate(ByVal message As String)
' Instantiation
Private myDelegate As MyDelegate = AddressOf DisplayMessage
' Method to be referenced
Shared Sub DisplayMessage(ByVal message As String)
	Console.WriteLine(message)
End Sub
' Invocation
myDelegate("Hello, Delegates!")
$vbLabelText   $csharpLabel

回調場景:利用委託提高靈活性

委派的一個主要用途是實現回調。 考慮在特定事件發生時,方法需要通知外部元件的情境。 委派提供了一種乾淨且模組化的解決方案:

class Program
{
static void Main(string [] args)
{
   public class EventPublisher
   {
       // Declare a delegate
       public delegate void EventHandler(string eventName);
       // Create an instance of the delegate
       public 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}");
       }
   }
}
}
class Program
{
static void Main(string [] args)
{
   public class EventPublisher
   {
       // Declare a delegate
       public delegate void EventHandler(string eventName);
       // Create an instance of the delegate
       public 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}");
       }
   }
}
}
Friend Class Program
Shared Sub Main(ByVal args() As String)
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'   public class EventPublisher
'   {
'	   ' Declare a delegate
'	   public delegate void EventHandler(string eventName);
'	   ' Create an instance of the delegate
'	   public EventHandler EventOccurred;
'	   ' Simulate an event
'	   public void SimulateEvent(string eventName)
'	   {
'		   ' Invoke the delegate to notify subscribers
'		   if (EventOccurred != Nothing)
'			   EventOccurred.Invoke(eventName);
'	   }
'   }
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'   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(string.Format("Event handled: {0}", 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)
    {
        return operation(operand1, operand2);
    }
}
// Usage
var calculator = new Calculator();
int result = calculator.PerformOperation((x, y) => x + y, 5, 3); // Adds 5 and 3
public delegate int MyDelegate(int x, int y);
public class Calculator
{
    public int PerformOperation(MyDelegate operation, int operand1, int operand2)
    {
        return operation(operand1, operand2);
    }
}
// Usage
var calculator = new Calculator();
int result = calculator.PerformOperation((x, y) => x + y, 5, 3); // Adds 5 and 3
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
		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
$vbLabelText   $csharpLabel

介紹 IronPDF:簡介

C# 委派(開發者如何使用它):圖 1 - IronPDF 網頁

了解更多 IronPDF 的功能,作為一個功能豐富的庫,旨在促進在 C# 應用程式中的 PDF 生成、操作和交互。 無論您是需要從頭開始建立 PDF、將 HTML 轉換為 PDF,還是從現有 PDF 中提取內容,IronPDF 提供了一套完整的工具來簡化這些任務。 它的多功能性使其成為開發者在各種專案中不可或缺的資產。

安裝 IronPDF:快速入門

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

Install-Package IronPdf

或者,您可以在 NuGet 套件管理器中搜尋 "IronPDF" 並從那裡安裝。

C# 委派(對開發人員的運作方式):圖 2 - 通過 NuGet 套件管理器安裝 IronPDF 庫

C# 中的委派:快速回顧

在 C# 中,委派充當类型安全的函數指標,允許方法被引用並作為參數傳遞。 如上所述,委託在不同情境中發揮著關鍵作用。 現在,問題來了:C# 委託是如何融入 IronPDF 的環境中,並能否有效地一起使用?

委派的整合與IronPDF

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

利用 IronPDF 使用委派的一種方式是透過文件事件的回調功能。 IronPDF提供可用委派訂閱的事件,允許您在文件生成過程的特定點執行自定義邏輯。 例如:

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");
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");
public delegate string AddPasswordEventHandler(PdfDocument e);
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")
public delegate String AddPasswordEventHandler(PdfDocument e)
$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 pdfDocument = new ChromePdfRenderer();
pdfDocument.RenderHtmlAsPdf($"<html><body>{getDynamicContent()}</body></html>").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 pdfDocument = new ChromePdfRenderer();
pdfDocument.RenderHtmlAsPdf($"<html><body>{getDynamicContent()}</body></html>").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 pdfDocument = New ChromePdfRenderer()
pdfDocument.RenderHtmlAsPdf($"<html><body>{getDynamicContent()}</body></html>").SaveAs("DynamicContentDocument.pdf")
$vbLabelText   $csharpLabel

在此範例中,getDynamicContent 委派動態生成 HTML 內容,然後將其嵌入 PDF 文件中。

C# Delegates(對開發人員的工作原理):圖 3 - 前面代碼輸出的 PDF

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

結論

總而言之,C# 委派是代碼靈活性和模組化的基石。 他們使開發人員能夠實現回調、處理事件,並接受函數式編程範式,例如以程式方式更改方法調用的能力。 作為 C# 工具包中的多功能工具,委派使開發人員能夠創建更具可維護性、可擴展性和表達力的代碼。 無論您是在構建事件驅動的應用程式、實現回呼機制,還是探討函數式程式設計,C#代理都是您程式設計旅程中的強大助手。

C# 委派和 IronPDF 可以形成合作的二重奏,提高應用程式中文件生成的功能。 無論您是在自訂文件事件或注入動態內容,委派(obj)提供了一種靈活的機制來擴展IronPDF的功能。 在您探索各種可能性時,請考慮專案的具體需求,以及如何透過 IronPDF 的委派功能來促成更加量身定制和動態的 PDF 生成過程。

IronPDF 提供免費試用,以測試其完整功能。 它可以從$749開始獲得商業使用許可

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
C# 屬性(開發人員如何運作)
下一個 >
C# 三元運算符(開發人員如何使用)