WPF 实现简易事件聚合

一直很心水棱镜(Prism)的事件聚合器。

看了下源代码,代码不多,但是东西真的不少。

简单的实现了一下,没有弱引用,没有线程安全,没有线程级别。

总的来说 原理还是很好理解的。

有点像观察者,或者说就是?

总共分为订阅,发布,通过一个单例总管。

内部设有一个字典和集合,保管引发实例和引发事件。

简单的画了个图

几处比较有意思的代码

字典保存对象

 public TArg GetEvent<TArg>() where TArg : EventBase, new()
        {
            if (!EventTypeName.TryGetValue(typeof(TArg), out EventBase eventBase))
            {
                var EventArgClass = new TArg();
                if (EventArgClass != null)
                {
                    EventTypeName[typeof(TArg)] = EventArgClass;
                }
                return EventArgClass;
            }
            else
                return (TArg)eventBase;
        }

引发事件

 public Action<object[]> DoAction()
        {
            if (this.Action != null)
            {
                return args =>
                {
                    if (args != null && args[0] != null)
                    {
                        var d = default(TArg);
                        d = (TArg)args[0];
                        ((Action<TArg>)Action)(d);
                    }
                };
            }
            return null;
        }

 使用方式

 public class Test : MethodSetting
    {
         
    }
    public class Test2 : MethodSetting<string>
    {

    }

    class Program
    {
        static void Main(string[] args)
        {
            EventManager.Instance.GetEvent<Test>().SetMethod(GetTest);
            EventManager.Instance.GetEvent<Test2>().SetMethod(GetTest2);
            EventManager.Instance.GetEvent<Test>().Push();
            EventManager.Instance.GetEvent<Test2>().Push("Test");
            EventManager.Instance.GetEvent<Test>().RemoveMethod(new Action(GetTest));
            EventManager.Instance.GetEvent<Test2>().RemoveMethod(new Action<string>(GetTest2));
            EventManager.Instance.GetEvent<Test>().Push();
            EventManager.Instance.GetEvent<Test2>().Push("Test");
        }

        private static void GetTest()
        {

        }
        private static void GetTest2(string obj)
        {

        }
    }

代码下载

原文地址:https://www.cnblogs.com/T-ARF/p/13592055.html