using DocumentFormat.OpenXml.Spreadsheet; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace MECF.Framework.Common { public interface IUserFunctions { void SwichValue(Dictionary parameter); void ValveTouchUp(Dictionary parameter); void MfcFlowTouchUp(Dictionary parameter); } public static class UserFunctionsEvents { private static readonly object lockObject = new object(); private static readonly Dictionary events = new Dictionary(); public static void ClearAll() { events.Clear(); } public static void RegisterEvent(string eventName, Action eventHandler) { lock (lockObject) { if (!events.ContainsKey(eventName)) { events[eventName] = null; } // 获取当前事件的委托 var currentDelegate = events[eventName] as Action; // 检查是否已经包含该处理器 if (currentDelegate != null) { // 使用 GetInvocationList() 检查处理器是否已在委托列表中 if (currentDelegate.GetInvocationList().All(d => d != (Delegate)eventHandler)) { // 只有当处理器不在委托列表中时才添加 currentDelegate += eventHandler; events[eventName] = currentDelegate; } } else { // 如果当前没有任何处理器,直接添加 currentDelegate = eventHandler; events[eventName] = currentDelegate; } } } public static void UnregisterEvent(string eventName, Action eventHandler) { lock (lockObject) { if (events.ContainsKey(eventName)) { var currentDelegate = (Action)events[eventName]; currentDelegate -= eventHandler; // 如果移除后没有其他处理器,可以选择从字典中移除键 if (currentDelegate == null) { events.Remove(eventName); } else { events[eventName] = currentDelegate; } } } } public static void RaiseEvent(string eventName, T args) { Action handler = null; lock (lockObject) { if (events.ContainsKey(eventName)) { handler = events[eventName] as Action; } } handler?.Invoke(args); } } }