[英]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.