C#事件管理
using System ;
using System. Collections. Generic ; public class EventMgr : BaseSingle< EventMgr>
{ public delegate void EventDelegate ( params object [ ] args) ; public delegate void EventDelegateED ( int eventDefine, params object [ ] args) ; private Dictionary< int , Delegate> _delegates = new Dictionary< int , Delegate> ( ) ; private Dictionary< int , Delegate> _delegatesED = new Dictionary< int , Delegate> ( ) ; public override void Init ( ) { base . Init ( ) ; Reset ( ) ; } public override void Reset ( ) { base . Reset ( ) ; _delegates. Clear ( ) ; _delegatesED. Clear ( ) ; } public void AddListener ( EventDefine ed, EventDelegate listener) { Delegate d; if ( _delegates. TryGetValue ( ( int ) ed, out d) ) { _delegates[ ( int ) ed] = Delegate. Combine ( d, listener) ; } else { _delegates[ ( int ) ed] = listener; } } public void AddListenerED ( EventDefine ed, EventDelegateED listener) { Delegate d; if ( _delegatesED. TryGetValue ( ( int ) ed, out d) ) { _delegatesED[ ( int ) ed] = Delegate. Combine ( d, listener) ; } else { _delegatesED[ ( int ) ed] = listener; } } public void RemoveListener ( EventDefine ed, EventDelegate listener) { Delegate d; if ( _delegates. TryGetValue ( ( int ) ed, out d) ) { Delegate currentDel = Delegate. Remove ( d, listener) ; if ( currentDel == null ) { _delegates. Remove ( ( int ) ed) ; } else { _delegates[ ( int ) ed] = currentDel; } } } public void RemoveListenerED ( EventDefine ed, EventDelegateED listener) { Delegate d; if ( _delegatesED. TryGetValue ( ( int ) ed, out d) ) { Delegate currentDel = Delegate. Remove ( d, listener) ; if ( currentDel == null ) { _delegatesED. Remove ( ( int ) ed) ; } else { _delegatesED[ ( int ) ed] = currentDel; } } } public void Trigger ( EventDefine ed, params object [ ] args) { Delegate d; if ( _delegates. TryGetValue ( ( int ) ed, out d) ) { var _d = d as EventDelegate ; _d?. Invoke ( args) ; } if ( _delegatesED. TryGetValue ( ( int ) ed, out d) ) { var _ed = d as EventDelegateED ; _ed?. Invoke ( ( int ) ed, args) ; } } public int GetEventDefineByName ( string name) { var ed = ( EventDefine) Enum. Parse ( typeof ( EventDefine ) , name) ; return ( int ) ed; }
}