zoukankan      html  css  js  c++  java
  • 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)
            {
    
            }
        }

    代码下载

  • 相关阅读:
    DDD 领域驱动设计-谈谈 Repository、IUnitOfWork 和 IDbContext 的实践
    UVA10071 Back to High School Physics
    UVA10071 Back to High School Physics
    UVA10055 Hashmat the Brave Warrior
    UVA10055 Hashmat the Brave Warrior
    UVA458 The Decoder
    UVA458 The Decoder
    HDU2054 A == B ?
    HDU2054 A == B ?
    POJ3414 Pots
  • 原文地址:https://www.cnblogs.com/T-ARF/p/13592055.html
Copyright © 2011-2022 走看看