class Program
{
static void Main(string[] args)
{
Sample11 s = new Sample11();
Console.Read();
}
} public class Sample11
{
public Sample11()
{
string path = @"D:\lassLibrary1Demo.dll";
Assembly ass = Assembly.LoadFile(path); Type tp = ass.GetType("lassLibrary1Demo.Sample1");
object tmpobj = ass.CreateInstance("lassLibrary1Demo.Sample1"); EventInfo eInfo = tp.GetEvent("ReturnBoolEvent");
Type handlerType = eInfo.EventHandlerType; MethodInfo inf = typeof(Sample11).GetMethod("WriteEvent", BindingFlags.Public | BindingFlags.Instance);
Delegate d0 = Delegate.CreateDelegate(handlerType, inf);//有问题,无法给委托绑定方法
eInfo.AddEventHandler(tmpobj, d0);
MethodInfo play0 = tp.GetMethod("Display");
string str0 = (string)play0.Invoke(tmpobj, null);
Console.WriteLine(str0);
} public bool WriteEvent(string s)
{
Console.WriteLine(s);
return true;
}
}DLL中的代码namespace lassLibrary1Demo
{
public class Sample1
{
public delegate bool ReturnBoolHandler(string info);
public event ReturnBoolHandler ReturnBoolEvent; /// <summary>
/// 显示
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public string Display()
{
if (ReturnBoolEvent != null)
ReturnBoolEvent("触发了返回bool值的事件");
return "无参数方法";
}
}
}
class Class1
{
public Class1()
{
string path = @"E:\Truner\lassLibrary1Demo\bin\Debug\lassLibrary1Demo.dll";
Assembly ass = Assembly.LoadFile(path); Type tp = ass.GetType("lassLibrary1Demo.Sample1");
object tmpobj = ass.CreateInstance("lassLibrary1Demo.Sample1"); EventInfo eInfo = tp.GetEvent("ReturnBoolEvent");
Type handlerType = eInfo.EventHandlerType; MethodInfo inf = typeof(Sampled).GetMethod("WriteEvent", BindingFlags.Public | BindingFlags.Instance); Sampled c = new Sampled();
Delegate d0 = Delegate.CreateDelegate(handlerType,c, inf,false);
eInfo.AddEventHandler(tmpobj, d0);
MethodInfo play0 = tp.GetMethod("Display");
string str0 = (string)play0.Invoke(tmpobj, null);
Console.WriteLine(str0);
}
}
public class Sampled
{
public bool WriteEvent(string s)
{
Console.WriteLine(s);
return true;
}
}
public class Pr_MainFrame
{ Assembly assembly = Assembly.Load(namescape1);
Object ucObj = assembly.CreateInstance(class1);
Type ucType = ucObj.GetType();
EventInfo ucEvent = ucType.GetEvent("Load");//获取“Load”事件
//绑定事件的新处理方法;
ucEvent.AddEventHandler(ucObj, new EventHandler(UcObjLoad));
public void UcObjLoad(object sender, System.EventArgs e)
{
progressBar.Visible = false;
//MessageBox.Show("OK");
}
}