[英]Generic type conversion in generic method
我有以下类(其中一些在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;
}
}
但是,即使aggregatedEvent的运行时类型为TestEvent,networkEvent始终为null。
您似乎希望称为NetworkEventBase<T>
的类在T
是协变的。 但是泛型类在C#中不能协变(泛型接口可以)。
有关此问题,请参阅其他线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.