.NET 幫助

C# 事件(開發者如何運作)

發佈 2025年1月14日
分享:

C# 中的事件是事件驅動編程的基礎部分。 它們允許物件進行通訊,並在某些相關事件發生時通知其他物件。 在本指南中,我們將探索事件以及如何宣告和使用它們。 讓我們一步一步地分解,以確保清晰的理解。 我們還將探索IronPDF在 C# 應用程式中進行 PDF 操作。

C# 的事件是什麼?

在 C# 中,事件允許物件之間的通信。 當事件被引發時,其他物件可以對其作出回應。 事件依賴於委派,委派作為方法的類型安全指針。 事件委派類型定義了可以處理公共事件的方法的簽名,以確保事件數據處理的一致性。

事件的核心組成部分

為了充分了解事件,我們來看一下它們的主要組成部分:

1. Publisher 類別

發布者類別是事件的來源。 負責宣告事件並在特定行動或條件發生時觸發它。 此過程通常涉及一個事件處理器方法來確定事件何時發生。 發布者還使用事件委託來定義可以處理事件的方法的簽名。 例如,在圖形用戶界面中(圖形用戶介面),按鈕控制項在引發「Click」事件時作為發佈者。

2. 訂閱者類別

訂閱者類別會監聽事件並作出反應。 訂閱者透過將事件處理方法附加到事件上來註冊其對事件的興趣。 當發布者觸發事件時,訂閱者的事件處理方法將執行。 單個事件可以有多個訂閱者,每個訂閱者在事件發生時都會有不同的回應。

3. 委派

委派是 C# 中事件的基礎。 它們是方法的類型安全指標,並定義了所有事件處理程序必須遵循的契約。 委派確保只有具有特定簽章的方法可以處理事件,提供一致且無錯誤的事件處理機制。

事件處理程式

事件處理程序是訂閱者類別中的方法,當事件觸發時會執行。 他們包含處理事件的邏輯,例如更新使用者介面、記錄數據或執行計算。 事件處理程序的簽章必須與事件關聯的委派型別相符。 此外,其他類別可以使用事件處理程序來回應共享事件。 這使得以模組化和可重用的方式實現事件變得更容易。

5. 事件數據

在許多情況下,事件需要向訂閱者傳達額外的信息。 這是通過使用事件數據類來實現的,這些類是從基礎的EventArgs類派生的。 事件資料包含有關事件的具體細節,例如消息、狀態或其他相關信息。

如何在C#中宣告和使用事件

步驟 1:宣告委派

委派定義事件處理程序的方法簽名。 在此範例中,我們建立一個委派來表示具有兩個參數的事件處理程式:object sender 和 EventArgs e。

public delegate void MyEventHandler(object sender, EventArgs e);
public delegate void MyEventHandler(object sender, EventArgs e);
Public Delegate Sub MyEventHandler(ByVal sender As Object, ByVal e As EventArgs)
VB   C#

步驟 2:宣告事件

事件是使用 event 關鍵字宣告的,並基於委派類型。 以下是一個範例:

public class Publisher
{
    public event MyEventHandler Notify; // Declare the event.
}
public class Publisher
{
    public event MyEventHandler Notify; // Declare the event.
}
Public Class Publisher
	Public Event Notify As MyEventHandler ' Declare the event.
End Class
VB   C#

步驟 3:引發事件

透過調用委派並傳遞必要的參數來引發事件。

public void TriggerEvent()
{
    if (Notify != null) // Check if there are subscribers.
    {
        Notify(this, EventArgs.Empty); // Raise the event.
    }
}
public void TriggerEvent()
{
    if (Notify != null) // Check if there are subscribers.
    {
        Notify(this, EventArgs.Empty); // Raise the event.
    }
}
Public Sub TriggerEvent()
	If Notify IsNot Nothing Then ' Check if there are subscribers.
		Notify(Me, EventArgs.Empty) ' Raise the event.
	End If
End Sub
VB   C#

步驟 4:訂閱事件

訂閱者使用 += 運算子註冊事件處理程式:

Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber();
publisher.Notify += subscriber.OnNotify; // Subscribe to the event.
Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber();
publisher.Notify += subscriber.OnNotify; // Subscribe to the event.
Dim publisher As New Publisher()
Dim subscriber As New Subscriber()
publisher.Notify += subscriber.OnNotify ' Subscribe to the event.
VB   C#

步驟 5:處理事件

事件處理器是在訂閱者類別中與委託簽名匹配的方法:

public void OnNotify(object sender, EventArgs e)
{
    Console.WriteLine("Event received!");
}
public void OnNotify(object sender, EventArgs e)
{
    Console.WriteLine("Event received!");
}
Public Sub OnNotify(ByVal sender As Object, ByVal e As EventArgs)
	Console.WriteLine("Event received!")
End Sub
VB   C#

IronPDF:C# PDF 庫

IronPDF 是一個多功能的庫,用於在 .NET 中處理 PDF,可以無縫整合到 C# 應用程式中。 結合 C# 中的事件,它可以提供一種動態方式來處理實時場景,例如進度更新、錯誤處理或通知。PDF 生成或操作。 讓我們以一種有趣的方式探索這種關係。 在 C# 中,事件 是用來表示某事發生的一種方式。 它們允許您的程序的一部分通知其他部分有關特定事件,例如處理文件、任務完成或遇到錯誤。

IronPDF 如何契合?

IronPDF 允許您生成、修改和保護 PDF,並將其與事件集成可以使您的應用程序更加互動。例如:

  • 進度追蹤:在生成大型 PDF 報告時通知訂閱者完成的百分比。
  • 錯誤處理:如果在 PDF 渲染或保存過程中出現問題,觸發事件。
  • 自訂動作:在特定的 PDF 操作後,執行自訂邏輯,如記錄或 UI 更新。

範例:使用事件通知生成 PDF

以下是一個使用 IronPDF 處理事件的簡單示例:

using IronPdf;
using System;
// Program class
class Program
{
    // Define a custom event for progress updates
    public static event Action<int> ProgressUpdated;
   // public static void Main
    public static void Main()
    {
        License.LicenseKey = "License-Key";
        // Subscribe to the ProgressUpdated event
        ProgressUpdated += DisplayProgress;
        Console.WriteLine("Generating PDF...");
        GeneratePdf();
    }
    static void GeneratePdf()
    {
        try
        {
            var Renderer = new ChromePdfRenderer();
            for (int i = 0; i <= 100; i += 20)
            {
                // Simulate progress
                System.Threading.Thread.Sleep(500);
                ProgressUpdated?.Invoke(i); // Trigger event with progress value
            }
            // Generate a PDF
            var PdfDocument = Renderer.RenderHtmlAsPdf("<h1>Hello, IronPDF with Events!</h1>");
            PdfDocument.SaveAs("IronPDF\example.pdf");
            ProgressUpdated?.Invoke(100); // Final update
            Console.WriteLine("PDF generated successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
    static void DisplayProgress(int progress)
    {
        Console.WriteLine($"Progress: {progress}%");
    }
}
using IronPdf;
using System;
// Program class
class Program
{
    // Define a custom event for progress updates
    public static event Action<int> ProgressUpdated;
   // public static void Main
    public static void Main()
    {
        License.LicenseKey = "License-Key";
        // Subscribe to the ProgressUpdated event
        ProgressUpdated += DisplayProgress;
        Console.WriteLine("Generating PDF...");
        GeneratePdf();
    }
    static void GeneratePdf()
    {
        try
        {
            var Renderer = new ChromePdfRenderer();
            for (int i = 0; i <= 100; i += 20)
            {
                // Simulate progress
                System.Threading.Thread.Sleep(500);
                ProgressUpdated?.Invoke(i); // Trigger event with progress value
            }
            // Generate a PDF
            var PdfDocument = Renderer.RenderHtmlAsPdf("<h1>Hello, IronPDF with Events!</h1>");
            PdfDocument.SaveAs("IronPDF\example.pdf");
            ProgressUpdated?.Invoke(100); // Final update
            Console.WriteLine("PDF generated successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
    static void DisplayProgress(int progress)
    {
        Console.WriteLine($"Progress: {progress}%");
    }
}
Imports IronPdf
Imports System
' Program class
Friend Class Program
	' Define a custom event for progress updates
	Public Shared Event ProgressUpdated As Action(Of Integer)
   ' public static void Main
	Public Shared Sub Main()
		License.LicenseKey = "License-Key"
		' Subscribe to the ProgressUpdated event
		AddHandler Me.ProgressUpdated, AddressOf DisplayProgress
		Console.WriteLine("Generating PDF...")
		GeneratePdf()
	End Sub
	Private Shared Sub GeneratePdf()
		Try
			Dim Renderer = New ChromePdfRenderer()
			For i As Integer = 0 To 100 Step 20
				' Simulate progress
				System.Threading.Thread.Sleep(500)
				RaiseEvent ProgressUpdated(i)
			Next i
			' Generate a PDF
			Dim PdfDocument = Renderer.RenderHtmlAsPdf("<h1>Hello, IronPDF with Events!</h1>")
			PdfDocument.SaveAs("IronPDF\example.pdf")
			RaiseEvent ProgressUpdated(100)
			Console.WriteLine("PDF generated successfully!")
		Catch ex As Exception
			Console.WriteLine($"Error: {ex.Message}")
		End Try
	End Sub
	Private Shared Sub DisplayProgress(ByVal progress As Integer)
		Console.WriteLine($"Progress: {progress}%")
	End Sub
End Class
VB   C#

C# 事件(開發人員如何運作):圖 1 - 輸出

結論

C# 事件(開發人員如何運作):圖 2 - 授權

在 C# 中結合 IronPDF 時,事件可以創建出一個強大的系統,用於動態 PDF 的生成和管理。 事件提供了一種清晰、高效的方式來異步處理 PDF 操作,而 IronPDF 提供了強大的功能,能在 .NET 平台上進行 PDF 的創建、編輯和操作。 IronPDF 提供一個免費試用測試所有功能而無限制。 商業許可證起價為 $749,可提供訪問完整的 PDF 生成和處理功能套件。

< 上一頁
C# Enumerable(對開發者而言的運作方式)
下一個 >
C# Async Await(對開發人員的運作原理)