Ben Cracknell
Ben Cracknell

Reputation: 271

Polymorphic generics (or something similar)

I'm not really sure how to word what I want, so I'll just show the code that isn't working:

abstract class EventListener<T> where T : IEvent
{
}

interface IEvent
{
}

/*
 * Simplified a bit, normally this class would use a dictionary of event listeners
 */
class Manager
{
    private EventListener<IEvent> listener;

    public void RegisterListener<T>(EventListener<T> subject) where T : IEvent
    {
        // here is the issue
        listener = subject;
    }
}

/*
 *  Implementation
 */

class FooEvent : IEvent
{
}

class FooListener : EventListener<FooEvent>
{
}

The issue occurs when I try to assign subject to listener. I tried casting before assigning, but had a similar problem:

EventListener<IEvent> casted = subject as EventListener<IEvent>;
events.Add(typeof(T), casted);

Is there a way to make this work?

Upvotes: 1

Views: 58

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

  1. Add non-generic interface IEventListener:

    interface IEventListener
    { }
    
  2. Implement it by your EventListener<T> class:

     abstract class EventListener<T> : IEventListener where T : IEvent
    {
    }
    
  3. Change your Manager.listener field type to IEventListener:

    private IEventListener listener;
    

Upvotes: 1

Related Questions