using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using XericLibrary.Runtime.Type; namespace XericLibrary.Runtime.Security { /// /// 程序流程保全 /// public class ProgramFlowSecurityExtend : WeaklyObject { #region 字段属性 /// /// 可扩展事件 /// public event Action ExtensibleDelegation { add { if(!DelegateContains(value)) DelegateAdd(value); } remove { DelegateRemove(value); } } /// /// 事件列表 /// private List delegateList; #endregion #region 类内类 /// /// 事件扩展标识 /// public class DelegateExtensibleFlag { /// /// 事件 /// public Action Event; /// /// 单步执行 /// public bool Doonce; /// /// 调用保护 /// public bool Conservate; public DelegateExtensibleFlag(Action action, bool doonce = false) { this.Event = action; this.Doonce = doonce; this.Conservate = false; } public override bool Equals(object obj) { if(obj is DelegateExtensibleFlag def) return def.Event == this.Event; return false; } public override int GetHashCode() { return Event.GetHashCode(); } } public DelegateExtensibleFlag DelegateFind(Action action) { return delegateList .Where(a => a.Event == action) .FirstOrDefault(); } public bool DelegateContains(Action action) { return DelegateFind(action) == null; } public void DelegateAdd(Action action, bool doonce = false) { delegateList.Add(new DelegateExtensibleFlag(action, doonce)); } public bool DelegateRemove(Action action) { return delegateList.Remove(new DelegateExtensibleFlag(action)); } #endregion #region 构造 public ProgramFlowSecurityExtend() { } #endregion #region 主要流程 /// /// 调用所有的已注册扩展事件,注意:这会比使用繁琐的外部方法更慢。 /// public void InvokedAllDelegate() { for(int i = 0; i < delegateList.Count; i++) { if(delegateList[i].Conservate) continue; try { delegateList[i].Event.Invoke(); } catch(Exception e) { delegateList[i].Conservate = true; Debug.LogError(e); } } } #endregion } }