这是我试图从中学习的场景:
- 有时会有 DLL 文件引发事件。
- DLL 文件不能添加到源代码中的引用,但它在磁盘上可用,并且程序可以在运行时访问它。
- 我将 DLL 文件加载为运行时的程序集。
- 我正在尝试从 DLL 订阅事件(我知道签名和参数格式),并在我的程序中处理它们。
程序集是一个简单的 Dll,其方法是添加其两个参数并使用自定义参数引发事件,包括求和运算的结果。这是DLL的代码:
namespace Dll1
{
public class Class1
{
public int c = 0;
public void add(int a, int b)
{
c = a + b;
if (Added !=null)
Added(this, new AddArgs(c));
}
public delegate void AddHandler(object sender, AddArgs e);
public event AddHandler Added;
}
public class AddArgs : EventArgs
{
private int intResult;
public AddArgs(int _Value)
{
intResult = _Value;
}
public int Result
{
get { return intResult; }
}
}
}
然后,在我的程序中,我使用 Assembly.LoadFile 加载了该 DLL。我的程序中有另一个名为EventProcessor的类,它包含一个事件处理程序来处理来自加载的程序集的事件:
namespace ConsoleApplication1
{
class Program
{
static Type[] parmTypes;
static void Main(string[] args)
{
Assembly asm = Assembly.LoadFile(@"C:\Projects\Dll1.Dll");
Type typ = asm.GetType("DLL1.Class1", true, true);
var method = typ.GetMethod("add");
EventInfo eInfo = typ.GetEvents()[0];
var obj = Activator.CreateInstance(typ);
EventProcessor evProc = new EventProcessor();
Type myTypeObj = evProc.GetType();
MethodInfo myMethodInfo = myTypeObj.GetMethod("myEventHandler");
Delegate d = Delegate.CreateDelegate(myTypeObj, myMethodInfo, true); // Error!
eInfo.AddEventHandler(obj, d);
method.Invoke(obj, new object[] { 1, 0 });
}
}
}
但是,当运行程序时,我收到一条错误消息“类型必须从委托派生。参数名称:类型”。我在这里做错了什么?或者有没有更好的方法来处理这种情况?如果有帮助,我还在最后添加了我的事件处理程序类。
namespace ConsoleApplication1
{
class EventProcessor
{
public void myEventHandler(object sender, AddArgs args)
{
Console.WriteLine("Event Received.");
}
}
public class AddArgs : EventArgs
{
private int intResult;
public AddArgs(int _Value)
{
intResult = _Value;
}
public int Result
{
get { return intResult; }
}
}
}
提前致谢。