Reputation: 271
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
Reputation: 125620
Add non-generic interface IEventListener
:
interface IEventListener
{ }
Implement it by your EventListener<T>
class:
abstract class EventListener<T> : IEventListener where T : IEvent
{
}
Change your Manager.listener
field type to IEventListener
:
private IEventListener listener;
Upvotes: 1