使用反射,调用方法是会写了,注册事件搞了好久搞不定,特求助大神!
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() { } } }
注册接收搞不定,请大神指点,谢谢!
我猜测你是想这样把:
using System;
using System.Reflection;
namespace bowen1
{
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");
var theEvent = typeClass.GetEvent("OnMessage");
Delegate mDelegate = Delegate.CreateDelegate(typeof(Action<string>), new Program(), "Recieve");
theEvent.AddEventHandler(obj, mDelegate);
method.Invoke(obj, null);
Console.ReadKey();
}
public void Recieve(string message)
{
Console.WriteLine(message);
}
}
}
你对Delegate.CreateDelegate
方法的理解有误
感谢你的支持,我已经用接口的方式解决了。
https://www.codeproject.com/Answers/5278974/How-to-reflection-one-DLL-and-register-its-action#answer2
用您的方法可以编译成功,但执行报异常。
@TabZhang: 报什么错
@TabZhang: 我这里成功执行了