在C#中,實現事件驅動的松耦合設計需要遵循一些關鍵原則。以下是一些建議:
public interface IEventHandler
{
void OnEventOccurred(object sender, EventArgs e);
}
public class WeakEventHandler<TEventArgs> where TEventArgs : EventArgs
{
private readonly WeakReference _handlerReference;
public WeakEventHandler(Action<object, TEventArgs> handler)
{
_handlerReference = new WeakReference(handler);
}
public void OnEventOccurred(object sender, TEventArgs e)
{
var handler = (Action<object, TEventArgs>)_handlerReference.Target;
if (handler != null && handler.Method != null)
{
handler(sender, e);
}
}
}
public class EventPublisher
{
public event IEventHandler EventOccurred;
protected virtual void OnEventOccurred(object sender, EventArgs e)
{
EventOccurred?.Invoke(this, e);
}
}
public class EventSubscriber : IEventHandler
{
public void OnEventOccurred(object sender, EventArgs e)
{
// 處理事件
}
}
var publisher = new EventPublisher();
var subscriber = new EventSubscriber();
var weakEventHandler = new WeakEventHandler<EventArgs>(subscriber.OnEventOccurred);
publisher.EventOccurred += weakEventHandler.OnEventOccurred;
遵循這些建議,可以在C#中實現基于事件的松耦合設計。