在C#中,委托和事件是实现消息传递和解耦的一种有效机制。委托是一种类型,它允许你将方法作为参数传递给其他方法,而事件则是基于委托的一种特殊类型,用于在特定情况下通知其他对象。
以下是如何使用委托和事件实现消息传递的步骤:
delegate
关键字。public delegate void MessageHandler(string message);
public class MessagePublisher
{
public event MessageHandler MessageReceived;
public void SendMessage(string message)
{
// 处理消息的逻辑
Console.WriteLine($"Received message: {message}");
// 通知订阅者
MessageReceived?.Invoke(message);
}
}
public class MessageSubscriber
{
public void Subscribe(MessagePublisher publisher)
{
publisher.MessageReceived += OnMessageReceived;
}
public void Unsubscribe(MessagePublisher publisher)
{
publisher.MessageReceived -= OnMessageReceived;
}
private void OnMessageReceived(string message)
{
Console.WriteLine($"Message subscriber received message: {message}");
}
}
class Program
{
static void Main(string[] args)
{
MessagePublisher publisher = new MessagePublisher();
MessageSubscriber subscriber = new MessageSubscriber();
// 订阅事件
subscriber.Subscribe(publisher);
// 发送消息
publisher.SendMessage("Hello, World!");
// 取消订阅事件
subscriber.Unsubscribe(publisher);
}
}
运行此程序,你将看到以下输出:
Received message: Hello, World!
Message subscriber received message: Hello, World!
这个例子展示了如何使用委托和事件实现消息传递。当SendMessage
方法被调用时,它会触发MessageReceived
事件,从而通知所有订阅该事件的MessageSubscriber
对象。