2013-07-18 66 views
-1

我有以下的類(其中有些是在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的實例轉換到它的基類NetworkEventBase在IEventAggregator的裝飾器中。 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始終爲空,即使aggregatedEvent的運行時類型是TestEvent。

+0

請編輯樣本,以清楚「networkEvent」來自哪裏。 –

+1

國家安全局已經發布了PRISM的框架? scnr – JeffRSon

回答

1

你似乎希望稱爲NetworkEventBase<T>將在T協變的。但泛型類不能在C#中共變(通用接口可以)。

查看關於此問題的其他線程。

+0

謝謝,我現在創建了一個接口,該接口定義了將IMessageBusAdapter注入事件的方法。 – cguedel