.NET 帮助

C# 事件(开发人员的工作原理)

发布 2025年一月14日
分享:

C# 中的事件是事件驱动编程的基本组成部分。 它们允许对象进行通信,并在发生感兴趣的事情时通知其他对象。 在本指南中,我们将探索事件以及如何声明和使用它们。 让我们一步一步地进行分解,以确保清晰的理解。 我们还将探索IronPDF用于C#应用程序中的PDF操作。

C#中的事件是什么?

C# 中的事件使对象之间能够进行通信。 当事件被触发时,其他对象可以对此作出响应。 事件依赖于委托,它们充当方法的类型安全指针。 事件委托类型定义了可以处理公共事件的方法的签名,确保事件数据处理的一致性。

事件的核心组件

为了全面了解事件,我们来看一下它们的主要组成部分:

发布者类

发布者类是事件的来源。 它负责声明事件并在特定动作或条件发生时触发事件。 此过程通常涉及一个事件处理方法来确定事件何时发生。 发布者还使用事件委托定义可以处理该事件的方法的签名。 例如,在图形用户界面中(图形用户界面),一个按钮控件在触发“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 操作后执行自定义逻辑,例如日志记录或用户界面更新。

示例:生成带有事件通知的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# 异步等待(开发人员工作原理)