我有以下类(其中一些在 PRISM 框架中,无法更改):
public abstract class NetworkEventBase<T> : CompositePresentationEvent<T> where T : NetworkEventPayload { }
public class NetworkEventPayload { }
public class TestEvent : NetworkEventBase<TestPayload> { }
public class TestPayload : NetworkEventPayload { }
// the following classes are PRISM classes:
public class CompositePresentationEvent<TPayload> : EventBase { }
public abstract class EventBase { }
现在我需要在 IEventAggregator 的装饰器中将 TestEvent 的实例转换为其基类 NetworkEventBase。IEventAggregator 看起来像:
public interface IEventAggregator
{
TEventType GetEvent<TEventType>() where TEventType : EventBase, new();
}
现在在我的装饰器中,我尝试像这样转换:
public class MessageBusAdapterInjectorDecorator : IEventAggregator {
...
public TEventType GetEvent<TEventType>() where TEventType : EventBase, new()
{
var aggregatedEvent = this.eventAggregator.GetEvent<TEventType>();
var networkEvent = aggregatedEvent as NetworkEventBase<NetworkEventPayload>;
if (networkEvent != null)
{
networkEvent.MessageBusAdapter = this.messageBusAdapter;
}
return aggregatedEvent;
}
}
但是,networkEvent 始终为 null,即使聚合事件的运行时类型为 TestEvent。