0

我有以下类(其中一些在 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。

4

1 回答 1

1

您似乎希望被调用的NetworkEventBase<T>T. 但是泛型类在 C# 中不能是协变的(泛型接口可以)。

请参阅有关此问题的其他线程。

于 2013-07-18T08:15:08.290 回答