我想使用反射订阅 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/