123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- 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<string, object> parameter);
- void ValveTouchUp(Dictionary<string, object> parameter);
- void MfcFlowTouchUp(Dictionary<string, object> parameter);
- }
- public static class UserFunctionsEvents
- {
- private static readonly object lockObject = new object();
- private static readonly Dictionary<string, Delegate> events = new Dictionary<string, Delegate>();
- public static void ClearAll()
- {
- events.Clear();
- }
- public static void RegisterEvent<T>(string eventName, Action<T> eventHandler)
- {
- lock (lockObject)
- {
- if (!events.ContainsKey(eventName))
- {
- events[eventName] = null;
- }
- // 获取当前事件的委托
- var currentDelegate = events[eventName] as Action<T>;
- // 检查是否已经包含该处理器
- 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<T>(string eventName, Action<T> eventHandler)
- {
- lock (lockObject)
- {
- if (events.ContainsKey(eventName))
- {
- var currentDelegate = (Action<T>)events[eventName];
- currentDelegate -= eventHandler;
- // 如果移除后没有其他处理器,可以选择从字典中移除键
- if (currentDelegate == null)
- {
- events.Remove(eventName);
- }
- else
- {
- events[eventName] = currentDelegate;
- }
- }
- }
- }
- public static void RaiseEvent<T>(string eventName, T args)
- {
- Action<T> handler = null;
- lock (lockObject)
- {
- if (events.ContainsKey(eventName))
- {
- handler = events[eventName] as Action<T>;
- }
- }
- handler?.Invoke(args);
- }
- }
- }
|