0

我正在尝试使用反射调用 Prism EventAggregator,因为事件有效负载是在运行时确定的。

以下是使用 EventAggregator 的常规方法:

        [TestMethod]
    public void WhenEventIsPublishedTheSubscriberReceivesIt()
    {
        var eventAggregator = new EventAggregator();

        eventAggregator.GetEvent<PubSubEvent<string>>().Subscribe(Subscription);
        eventAggregator.GetEvent<PubSubEvent<string>>().Publish(Constants.TestSymbol);

        Assert.IsTrue(this.subscriptionReceived);
    }

    private void Subscription(string data)
    {
        this.subscriptionReceived = true;
    }

我正在这样做:

            var commandHandlerLocator = this.container.Resolve<ICommandHandlerLocator>();

        var t = command.GetType();

        dynamic commandHandler = commandHandlerLocator.GetType()
            .GetMethod("GetCommandHandler")
                .MakeGenericMethod(command.GetType()).Invoke(commandHandlerLocator, null);

        IEnumerable<IEvent> events = commandHandler.Execute(command);

        foreach (var @event in events)
        {
            var typedEvent = typeof(PubSubEvent<>).MakeGenericType(@event.GetType());

            dynamic pubSubEvent = this.eventAggregator.GetType()
                .GetMethod("GetEvent")
                    .MakeGenericMethod(typedEvent).Invoke(this.eventAggregator, null);

            pubSubEvent.Publish(@event);
        }

在这里您可以看到方法和方法参数变量

在我看来很好。但是当我执行最后一行“(pubSubEvent.Publish(@event);”时,我得到了异常,即使用无效参数调用发布方法。知道为什么@event参数无效吗?

问候!

4

1 回答 1

0

找到了答案。我需要强烈键入@event:

        private void Publish<T>(T @event) where T : IEvent
    {
        var eventAggregator = new EventAggregator();
        var pubSubEventType = typeof(PubSubEvent<>).MakeGenericType(typeof(T));

        dynamic pubSubEvent = eventAggregator.GetType()
                    .GetMethod("GetEvent")
                        .MakeGenericMethod(pubSubEventType).Invoke(eventAggregator, null);

        pubSubEvent.Publish(@event);
    }
于 2015-05-18T17:41:53.507 回答