在C#中,委托和事件是用于實現事件驅動編程的重要工具。它們可以幫助我們更好地組織和管理代碼,提高代碼的可讀性和可維護性。以下是一些建議,可以幫助你優化C#中的委托和事件代碼結構:
Delegate
關鍵字。這樣可以提高代碼的可讀性和類型安全性。例如,定義一個強類型委托,用于處理特定類型的事件:public delegate void MyEventHandler(object sender, MyEventArgs e);
public event MyEventHandler MyEvent;
public class EventPublisher
{
public event MyEventHandler MyEvent;
protected virtual void OnMyEvent(MyEventArgs e)
{
MyEvent?.Invoke(this, e);
}
}
public class EventSubscriber
{
public EventSubscriber(EventPublisher publisher)
{
publisher.MyEvent += OnMyEvent;
}
private void OnMyEvent(object sender, MyEventArgs e)
{
// 處理事件邏輯
}
}
public class EventPublisher
{
private readonly WeakEventSubscription<MyEventHandler> _myEventSubscription;
public event MyEventHandler MyEvent;
public EventPublisher(EventSubscriber subscriber)
{
_myEventSubscription = new WeakEventSubscription<MyEventHandler>(subscriber, OnMyEvent);
}
protected virtual void OnMyEvent(object sender, MyEventArgs e)
{
MyEvent?.Invoke(this, e);
}
}
public class WeakEventSubscription<TEventHandler> where TEventHandler : Delegate
{
private readonly WeakReference _handlerReference;
private readonly Action<object, TEventArgs> _eventHandler;
public WeakEventSubscription(EventSubscriber subscriber, Action<object, TEventArgs> eventHandler)
{
_handlerReference = new WeakReference(subscriber);
_eventHandler = eventHandler;
}
public void Remove()
{
var handler = _handlerReference.Target as EventSubscriber;
if (handler != null)
{
((EventPublisher)handler._publisher).MyEvent -= _eventHandler;
}
}
}
public delegate TEventArgs EventHandler<TEventArgs>(object sender, TEventArgs e);
public event EventHandler<MyEventArgs> MyEvent;
遵循以上建議,可以幫助你優化C#中的委托和事件代碼結構,提高代碼的可讀性和可維護性。