c#动态加载dll时怎样处理dll事件
dll代码:
namespace ClassLibrary
{
public class Class1
{
public delegate void callback_delegate(string str);
public event callback_delegate callback_event;
public void Fun5(string str)
{
ShowCallBack();
}
public void ShowCallBack()
{
callback_event("aaaaaaaaa");
}
}
}
调用代码:
Assembly assembly = Assembly.LoadFile(m_dll_path);
Type type = assembly.GetType("ClassLibrary.Class1");
Object obj = Activator.CreateInstance(type);
BindingFlags mybindingFlags = BindingFlags.Instance | BindingFlags.Public;
EventInfo eventInfo = obj.GetType().GetEvent("callback_event", mybindingFlags);
var mycallback = typeof(Program).GetMethod("ShowMsg",BindingFlags.Static|BindingFlags.NonPublic);
Delegate del = Delegate.CreateDelegate(eventInfo.EventHandlerType,null, mycallback);
eventInfo.AddEventHandler(obj,del);
MethodInfo methodInfo = type.GetMethod("Fun5");
string ret = methodInfo.Invoke(obj, new object[] { "123"}) as string;
还有mycallback为空