C# 关于反射事件

时间:2022-04-17 06:05:28

在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就是返回值。