泛型方法中的泛型类型转换

时间:2013-07-18 07:58:18

标签: c# prism-4

我有以下类(其中一些属于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 { }

现在我需要将一个TestEvent实例转换为IEventAggregator装饰器内的基类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;
    }
}

但是,即使aggregateatedEvent的运行时类型是TestEvent,networkEvent也始终为null。

1 个答案:

答案 0 :(得分:1)

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

请参阅此问题的其他主题。