zoukankan      html  css  js  c++  java
  • C# 关于反射事件

    在frmMain类中的代码

    private void StartRun(string tag, string date, bool tipType)
            {
                var dllPath = string.Format("{0}.{1}", GetType().Namespace, tag);
                var assembly = Assembly.Load(dllPath);
                var classFullPath = string.Format("{0}.{1}.{2}", GetType().Namespace, tag, "RunBTW");
                var type = assembly.GetType(classFullPath);
                object instance = assembly.CreateInstance(classFullPath);
                var eventInfo = type.GetEvent("AppendTips", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static);
                var tDelegate = eventInfo.EventHandlerType;

                var miHandler = typeof(frmMain).GetMethod("AppendTips", BindingFlags.Public | BindingFlags.Static);
                var d = Delegate.CreateDelegate(tDelegate, miHandler);
                var miAddHandler = eventInfo.GetAddMethod();
                object[] addHandlerArgs = { d };
                miAddHandler.Invoke(instance, addHandlerArgs);

                var method = type.GetMethod("StartRun");
                method.Invoke(instance, new object[] { date, tipType });
            }

            public static void AppendTips(string tips, Color color, bool tipsType)
            {
                if (frm.richResultAuto.InvokeRequired)
                {
                    AppendTipsDelegate atd = new AppendTipsDelegate(Tips);
                    frm.Invoke(atd, new object[] { tips, color, tipsType });
                }
                else
                {
                    Tips(tips, color, tipsType);
                }
            }

    动态加载dll文件Assembly.Load加载的是相对路径 而Assembly.LoadFile需要一个绝对路径

    frmMain类中的AppendTips方法必须是public static 不然绑定不了。

      var eventInfo = type.GetEvent("AppendTips", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static);中的AppendTips这里是反射了RunBTW类中的AppendTips事件名称。

    public class RunBTW
      {

          public delegate void AppendTipsDelegate(string tips, Color color, bool tipsType);

          public event AppendTipsDelegate AppendTips;

          public void StartRun(string date, bool tipsType)
          {

       }

    }

    RunBTW中的StartRun方法是没有返回值如果有返回值,比如说返回一个int类型

    var cusRerurnValue=  method.Invoke(instance, new object[] { date, tipType });

    这里的cusRerurnValue就是返回值。

    参考自:http://bbs.csdn.net/topics/330067707

    代码改变世界
  • 相关阅读:
    将训练好的Tensorflow模型部署到web应用中
    python pip升级
    python time
    python 队列模拟递归遍历目录(广度遍历)
    python 栈模拟递归遍历目录(深度遍历)
    python 递归遍历目录
    python 队列
    python 栈
    python 递归
    python 语音模块
  • 原文地址:https://www.cnblogs.com/oreobyzf/p/6244323.html
Copyright © 2011-2022 走看看