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)
            {
    
            }
        }

    代码下载

  • 相关阅读:
    用故事说透 HTTPS
    nginx部署基于http负载均衡器
    Jenkins使用docker-maven-plugin进行编译时发现没有权限
    Jenkins执行mvn -f ${project_name} clean package报错:找不到父工程
    Harbor的镜像上传和拉取
    java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeConverter
    Jenkins+SonarQube代码审查
    Centos7安装SonarQube7.9.3
    Centos7 rpm 安装Mysql5.7
    Jenkins 配置邮箱服务器发送构建结果
  • 原文地址:https://www.cnblogs.com/T-ARF/p/13592055.html
Copyright © 2011-2022 走看看