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

本文关键字:类型转换 泛型 泛型方法 | 更新日期: 2023-09-27 18:23:47

我有以下类(其中一些在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的decorator中将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;
    }
}

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

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

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

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