【发布时间】:2014-04-24 21:44:02
【问题描述】:
我有以下代码:
namespace ConsoleApplication
{
static void Main(string[] args)
{
Device device = new Device();
device.Command += new EventHandler<DeviceSpecialArgs>(device_Command);
}
public static void device_Command(Object source, DeviceSpecialArgs args)
{
Console.WriteLine("Command: {0}, Reguest: {1}", args.Command, args.Request);
}
}
}
我必须做完全相同的事情,但需要在运行时加载包含类型 Device 和 DeviceSpecialArgs 的程序集。我知道如何使用反射加载程序集,但我发现事件处理部分令人费解:
namespace ConsoleApplication
{
static void Main(string[] args)
{
// Load the assembly
string dllPath = @"C:\Temp\Device.dll"
Assembly asm = Assembly.LoadFrom(dllPath);
// Instanciate Device
Type deviceType = asm.GetType("Device");
object device = Activator.CreateInstance(deviceType);
// How do I subscribe to the Command event?
}
// args would normally be a DeviceSpecialArgs but since that type is
// unknown at compile time, how do I prototype the handler?
public static void device_Command(Object source, ??? args)
{
Console.WriteLine("Command: {0}, Reguest: {1}", args.Command, args.Request);
}
}
如何使用反射订阅事件?另外,由于“args”的类型在编译时未知,我应该如何对处理程序本身进行原型设计?仅供参考,我是 C# 3 和 .NET 3.5。
【问题讨论】:
-
看看这个帖子here。似乎是重复的。
-
此处强制执行类型安全,您必须使用类型与委托类型兼容的 e 参数编写事件处理程序。你得到的只是object。然后,您还需要对 e.GetType() 进行反思以挖掘出您需要的属性。
标签: c# reflection event-handling .net-3.5 c#-3.0