c# - 使用反射订阅 Prism EventAggregator 事件

标签 c# silverlight reflection prism eventaggregator

我想使用反射订阅 EventAggregator 事件,因为我试图在运行时动态连接 Prism 模块之间的事件订阅。 (我使用的是 Silverlight 5、Prism 和 MEF)。

我想要实现的是调用_eventAggregator.GetEvent<MyType>().Subscribe(MyAction)在我的一个模块中,但我一直在调用 _eventAggregator.GetEvent<MyType>() .我怎样才能从那里继续调用 Subscribe(MyAction)

假设我的事件类是 public class TestEvent : CompositePresentationEvent<string> { } .我在编译时不知道这一点,但我知道运行时的类型。

这是我目前得到的:

 Type myType = assembly.GetType(typeName); //get the type from string

 MethodInfo method = typeof(IEventAggregator).GetMethod("GetEvent");
 MethodInfo generic = method.MakeGenericMethod(myType);//get the EventAggregator.GetEvent<myType>() method

 generic.Invoke(_eventAggregator, null);//invoke _eventAggregator.GetEvent<myType>();

我非常感谢指向正确方向的指针。

最佳答案

您可以执行此操作而不必担心使用动态调用的事件的“类型”。

Type eventType = assembly.GetType(typeName);
MethodInfo method = typeof(IEventAggregator).GetMethod("GetEvent");
MethodInfo generic = method.MakeGenericMethod(eventType);
dynamic subscribeEvent = generic.Invoke(this.eventAggregator, null);

if(subscribeEvent != null)
{
    subscribeEvent.Subscribe(new Action<object>(GenericEventHandler));
}

//.... Somewhere else in the class

private void GenericEventHandler(object t)
{
}

现在您真的不需要知道“事件类型”是什么。

关于c# - 使用反射订阅 Prism EventAggregator 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13035320/

相关文章:

Node.js - 搜索 "util"模块;识别核心模块

java - 是否可以将检索到的类对象(通过反射)转换为接口(interface)?

c# - 如何检查变换 eulerAngles 是否位于 0,0,0,?

c# - 排序、过滤和分页 MVC

c# - 将 XML 转换为 C# 对象

javascript - 强制 SSRS 报告中的链接从 silverlight 中在新窗口中打开

c# - 将职责委派给 WinForm 控件——控件是否应该了解彼此的操作?

c# - 如何以编程方式设置 wpf 网格 rowspan?

silverlight - 当ViewModel属性更改时,如何启动动画?

c# - 是否可以使用来自托管代码的 C# 反射来调用非托管代码?