【问题标题】:Subscribe to Prism EventAggregator events with Reflection使用反射订阅 Prism EventAggregator 事件
【发布时间】:2012-10-23 16:41:44
【问题描述】:

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

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

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

这是我目前得到的:

 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>();

我真的很感激一个指向正确方向的指针。

【问题讨论】:

    标签: c# silverlight reflection prism eventaggregator


    【解决方案1】:

    您可以这样做,而不必担心使用动态调用的事件的“类型”。

    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)
    {
    }
    

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

    【讨论】:

      【解决方案2】:

      可以这么简单:

      var myEvent = generic.Invoke(eventAggregator, null) as CompositePresentationEvent<string>;
      if (myEvent != null) 
          myEvent.Subscribe(MyAction);
      

      假设您知道负载类型。

      就我个人而言,我将在模块外部使用的聚合事件视为该模块的 API,我尝试将它们放在某种共享程序集中,其他模块可以对其进行编译。

      【讨论】:

      • 好的,谢谢!我错过了as CompositePresentationEvent&lt;string&gt; 部分。
      【解决方案3】:

      我在这里找到了payload类型未知的情况的答案:

      http://compositewpf.codeplex.com/workitem/6244

      1. 添加EventAggregator.GetEvent(Type eventType) 获取不带泛型参数的事件

      2. 使用反射构建 Action 类型的表达式

      3. 使用反射订阅事件(即调用订阅方法)并将 Expression.Compile 作为参数传递。

      如果 KeepAlive 为真,则此方法有效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-23
        • 2011-09-14
        • 1970-01-01
        • 1970-01-01
        • 2011-08-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多