.NET 幫助

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

發佈 2024年2月18日
分享:

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

在本全面指南中,我們將深入探討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!")
VB   C#

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

委派的主要使用案例之一是實現回調。考慮以下場景:當一個方法需要在特定事件發生時通知外部組件。委派提供了一個乾淨且模組化的解決方案:

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
VB   C#

使用委派進行函數編程

委派在採用 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
VB   C#

介紹 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)
VB   C#

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

接下來,創建了一個名為 "StyledDocument.pdf" 的 PdfDocument 實例。宣告了一個與 AddPassword 方法具有相同簽名的委託,名為 AddPasswordEventHandler。委託的實例,名為 handler,被賦值為 AddPassword 方法。接著使用 Invoke 方法調用該委託,將 document 實例作為參數傳遞,並將返回的密碼賦予 documentPassword 屬性。

最後,調用 documentSaveAs 方法,將其儲存為 "PasswordProtected.pdf"。該代碼有效地使用委託來動態地根據 AddPassword 方法內的某些條件來確定和設置 PdfDocument 的密碼。

2. 使用委託動態設置內容

委託也可以用來在 PDF 文件中插入動態內容。IronPDF 支持插入 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")
VB   C#

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

C# 委派(對開發者的運作方式):圖 3 - 從之前的程式碼輸出的 PDF

要高效地使用 IronPDF,請訪問 文件 頁面。

結論

總而言之,C# 的委託是代碼靈活性和模塊化的基石。它們使開發人員能夠實現回調、處理事件並採用函數式編程範式,如可以編程方式更改方法調用。作為 C# 工具包中的一個多功能工具,委託使開發人員能夠創建更具可維護性、可擴展性和表達力的代碼。無論您是在構建事件驅動的應用程序、實現回調機制還是探索函數式編程,C# 的委託都是您編程旅程中的強大盟友。

C# 的委託和 IronPDF 可以形成合作雙人組,在應用程序中增強文檔生成的功能。無論您是在定制文檔事件還是注入動態內容,委託都提供了一種靈活的機制來擴展 IronPDF 的功能。在探索可能性時,請考慮項目的具體需求,以及委託如何有助於更量身定制和動態化的 PDF 生成過程與 IronPDF。

IronPDF 提供了一個 免費試用 測試其完整功能。它可以是 授權 用於商業用途,起價自 $749。

< 上一頁
C# 屬性(開發人員如何運作)
下一個 >
C# 三元運算符(開發人員如何使用)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >