使用反射注册Action<string>事件的求助
使用反射,调用方法是会写了,注册事件搞了好久搞不定,特求助大神!DLL代码为如下,编译为:RefTest.dll
程序代码:
using System; namespace RefTest { public class Test { public event Action<string> OnMessage; public void WriteString() { Console.WriteLine("Write String"); OnMessage?.Invoke("ActionMessage"); } } }
调用代码为:
程序代码:
using System; using System.Diagnostics; using System.Reflection; namespace ConsoleAppFixed { class Program { static void Main(string[] args) { //反射加载 Assembly assembly = Assembly.LoadFrom("RefTest.dll"); //加载程序集 Type typeClass = assembly.GetType("RefTest.Test"); //获取类型(命名空间.类名) object obj = Activator.CreateInstance(typeClass); //实例化 MethodInfo method = typeClass.GetMethod("WriteString"); //查找方法 method.Invoke(obj, null); //方法调用 //注册事件 var t = typeof(Action<string>); Delegate mDelegate = Delegate.CreateDelegate(t, obj, "OnMessage"); //这里不会注册了 Console.ReadKey(); } public static void Recieve() { } } }
注册接收搞不定,请大神指点,谢谢!