编辑
2025-09-19
C#
00

目录

引言
事件的基本概念
库存管理系统示例
步骤1: 定义事件
步骤2: 订阅事件
事件如何工作
C#中的重要事件模式
完整代码
结论

引言

在C#中,事件是一种强大的机制,允许对象之间进行松耦合的通信。事件遵循发布-订阅模式,其中一个对象(发布者)在特定操作发生时通知其他对象(订阅者)。本文将深入探讨如何在C#中订阅事件,并提供一个实际的库存管理系统示例来说明这一概念。

事件的基本概念

在C#中,事件建立在委托的基础之上。它们特别适用于一个对象需要通知其他对象某些重要事情已经发生的场景。让我们通过一个库存管理系统的例子来理解事件的工作原理。

库存管理系统示例

我们将创建一个简单的库存管理系统,当产品库存低于某个阈值时,系统会通知仓库管理员和供应商服务。

步骤1: 定义事件

首先,我们在InventoryManager类中定义一个StockLow事件。当商品库存低于5个单位时,将触发此事件。

C#
using System; public class StockEventArgs : EventArgs { public string ItemName { get; set; } public int CurrentStock { get; set; } } public class InventoryManager { public event EventHandler<StockEventArgs> StockLow; private int _stockLevel; public string ItemName { get; set; } public InventoryManager(string itemName, int initialStock) { ItemName = itemName; _stockLevel = initialStock; } public void ProcessSale(int quantity) { _stockLevel -= quantity; Console.WriteLine($"{quantity} {ItemName}(s) sold. Current stock: {_stockLevel}"); if (_stockLevel < 5) { OnStockLow(); } } protected virtual void OnStockLow() { StockLow?.Invoke(this, new StockEventArgs { ItemName = this.ItemName, CurrentStock = this._stockLevel }); } }

在这个例子中:

  • StockEventArgs类用于传递商品名称和当前库存信息给事件订阅者。
  • InventoryManager类跟踪产品库存,并在库存低于阈值时触发StockLow事件。

步骤2: 订阅事件

接下来,我们创建WarehouseManagerSupplierService类,它们将订阅StockLow事件。当库存水平低于阈值时,这些类将采取适当的行动。

C#
public class WarehouseManager { public void Restock(object sender, StockEventArgs e) { Console.WriteLine($"Warehouse notified: Restock {e.ItemName} (Current stock: {e.CurrentStock})"); } } public class SupplierService { public void NotifySupplier(object sender, StockEventArgs e) { Console.WriteLine($"Supplier notified to replenish stock for {e.ItemName}."); } } public class Program { public static void Main(string[] args) { InventoryManager inventory = new InventoryManager("Laptop", 10); WarehouseManager warehouse = new WarehouseManager(); SupplierService supplier = new SupplierService(); // 订阅StockLow事件 inventory.StockLow += warehouse.Restock; inventory.StockLow += supplier.NotifySupplier; // 模拟销售减少库存 inventory.ProcessSale(3); // 库存 = 7, 不触发事件 inventory.ProcessSale(4); // 库存 = 3, 触发事件 } }

在这个例子中:

  • WarehouseManagerSupplierService订阅了StockLow事件。
  • 当库存降至5以下时,两个订阅者都会收到通知,并触发相应的操作(补货和通知供应商)。

事件如何工作

在这个库存管理系统中:

  • InventoryManager作为发布者,当库存水平低于阈值时引发StockLow事件。
  • WarehouseManagerSupplierService作为订阅者,通过补货和通知供应商来响应事件。

C#中的重要事件模式

在使用C#事件时,请记住以下最佳实践:

  1. 使用**EventHandler**: 始终使用EventHandlerEventHandler<T>来遵循C#事件签名的约定。
  2. 取消订阅事件: 确保订阅者在不再需要时正确取消订阅事件,以避免内存泄漏。
  3. 顺序执行: 事件处理程序按添加的顺序执行,除非显式异步处理。

完整代码

以下是库存管理系统使用事件的完整C#代码:

C#
public class StockEventArgs : EventArgs { public string ItemName { get; set; } public int CurrentStock { get; set; } } public class InventoryManager { public event EventHandler<StockEventArgs> StockLow; private int _stockLevel; public string ItemName { get; set; } public InventoryManager(string itemName, int initialStock) { ItemName = itemName; _stockLevel = initialStock; } public void ProcessSale(int quantity) { _stockLevel -= quantity; Console.WriteLine($"{quantity} {ItemName}(s) 出售. 当前库存: {_stockLevel}"); if (_stockLevel < 5) { OnStockLow(); } } protected virtual void OnStockLow() { StockLow?.Invoke(this, new StockEventArgs { ItemName = this.ItemName, CurrentStock = this._stockLevel }); } } public class WarehouseManager { public void Restock(object sender, StockEventArgs e) { Console.WriteLine($"库存修改: {e.ItemName} (当前库存: {e.CurrentStock})"); } } public class SupplierService { public void NotifySupplier(object sender, StockEventArgs e) { Console.WriteLine($"通知供应商补充库存: {e.ItemName}."); } } public class Program { public static void Main(string[] args) { InventoryManager inventory = new InventoryManager("Laptop", 10); WarehouseManager warehouse = new WarehouseManager(); SupplierService supplier = new SupplierService(); // 订阅StockLow事件 inventory.StockLow += warehouse.Restock; inventory.StockLow += supplier.NotifySupplier; // 模拟销售减少库存 inventory.ProcessSale(3); // 库存 = 7, 不触发事件 inventory.ProcessSale(4); // 库存 = 3, 触发事件 } }

image.png

结论

事件是C#中实现应用程序不同部分之间通信的关键机制。它们允许组件之间的松耦合,使代码更易于维护和扩展。通过本文提供的库存管理系统示例,我们清楚地展示了如何在C#中有效使用和订阅事件。掌握事件处理将使您能够创建更灵活、可扩展的应用程序,并更好地应对实际开发场景中的各种挑战。

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!