在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
對象。