Frage

I have the following classes (some of them are in the PRISM framework and cannot be changed):

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 { }

Now I need to convert an instance of TestEvent to its base class NetworkEventBase inside a decorator for IEventAggregator. IEventAggregator looks like:

public interface IEventAggregator
{
    TEventType GetEvent<TEventType>() where TEventType : EventBase, new();
}

Now in my decorator I try to convert like this:

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;
    }
}

However, networkEvent is always null, even when the runtime type of aggregatedEvent is TestEvent.

War es hilfreich?

Lösung

You seem to hope that the class called NetworkEventBase<T> would be covariant in T. But generic classes can't be covariant in C# (generic interfaces can).

See other threads on this issue.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top