如何通过反射添加BackgroundWorker RunWorkerCompleted事件?
通常我会去:
bgwExportGrid.RunWorkerCompleted += ReportManager.RunWorkerCompleted;
ReportManager 类是一个静态类,包含我想要使用的事件处理程序。
public static class ReportManager
{
public static void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
...
}
}
现在我已经创建了一个BackgroundWorker,并希望附加ReportManager 中定义的RunWorkerCompleted 事件。 但是,无法引用 ReportManager,否则会发生循环引用,因此需要反射。
任何帮助将不胜感激。
我已经查看了以下内容,但还没有走得太远:
Assembly assem = Utils.GetAssembly("WinUI.Reporting.Common.dll");
Type reportManagerType = assem.GetModule("WinUI.Reporting.Common.dll").GetType("WinUI.Reporting.Common.ReportManager");
EventInfo evWorkerCompleted = reportManagerType.GetEvent("RunWorkerCompleted");
Type tDelegate = evWorkerCompleted.EventHandlerType;
Normally I would go:
bgwExportGrid.RunWorkerCompleted += ReportManager.RunWorkerCompleted;
The ReportManager class is a static class containing the event handler I want to use.
public static class ReportManager
{
public static void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
...
}
}
Now I have created a BackgroundWorker and want to attach the RunWorkerCompleted event as defined in ReportManager. However ReportManager cannot be referenced as otherwise a cyclic reference happens therefore reflection is needed.
Any help would be greatly appreciated.
I've looked at the following but haven't gotten very far:
Assembly assem = Utils.GetAssembly("WinUI.Reporting.Common.dll");
Type reportManagerType = assem.GetModule("WinUI.Reporting.Common.dll").GetType("WinUI.Reporting.Common.ReportManager");
EventInfo evWorkerCompleted = reportManagerType.GetEvent("RunWorkerCompleted");
Type tDelegate = evWorkerCompleted.EventHandlerType;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为,如果您将 ReportManager 中的接口抽象为两个程序集都可以引用的接口,那么您的代码将来会更容易维护。 但是,如果这不适合您,我认为您正在尝试实现类似的目标:
请注意
Form1
和EventHandlers
之间没有“硬”引用> 类,因此它可以是驻留在任何其他程序集中的任何其他类; 事件处理程序是根据类型名称和方法名称(当然,必须具有正确的签名)创建和附加的。I think your code would be easier to maintain in the future if you would instead abtract the interface out of the ReportManager into an interface that both assemblies can reference. But, if that is not an option for you, I think that you are trying to achieve something like this:
Note how there is no "hard" reference between
Form1
and theEventHandlers
class, so that could be any other class residing in any other assembly; the event handler is created and attached based on the name of the type and the name of the method (which, naturally, must have the correct signature).更新的答案:
Updated answer:
设法让它工作。 ReportManager 是一个静态类,因此不需要使用 Activator.CreateInstance。
Managed to get it working. ReportManager is a static class therefore there is no need to use Activator.CreateInstance.