C # override method with subclass parameter

I'm trying to achieve something like this

public abstract class BaseEvent
{
    public abstract void Dispatch(IEventHandler handler);
}

public class MyEvent : BaseEvent
{
    public override void Dispatch(IMyEventHandler handler)
    {
        handler.OnMyEvent(this);
    }
}

public interface IEventHandler
{
}

public interface IMyEventHandler : IEventHandler
{
    void OnMyEvent(MyEvent e);
}

The problem is that the compiler complains that it MyEventdoes not implement BaseEventbecause it Dispatchaccepts IMyEventHandlerinstead IEventHandler. I don’t want to MyEvent.Dispatchtake IEventHandlerit and then apply it to IMyEventHandler, because I would like to do a compile-time check to make sure that I am not doing something stupid, like passing in some other event handler. I found a possible solution (below), but I am wondering if there is a better way to do this.

public abstract class BaseEvent<H> where H : IEventHandler
{
    public abstract void Dispatch(H handler);
}

public class MyFirstEvent<H> : BaseEvent<H> where H : IMyFirstEventHandler
{
    public override void Dispatch(H handler)
    {
        handler.OnMyFirstEvent(this);
    }
}

public interface IEventHandler
{
}

public interface IMyFirstEventHandler : IEventHandler
{
    void OnMyFirstEvent<H>(MyFirstEvent<H> e) where H : IMyFirstEventHandler;
}

Thanks Tom

+5
source share
3 answers

I have used your approach before.

It looks pretty solid for me.

+3
source

MyEvent . . .

.

public class MyEvent : BaseEvent
{
    public override void Dispatch(IEventHandler handler)
    {
        if(!handler is IMyFirstEventHandler )throw new ArgumentException("message").
        ((IMyFirstEventHandler )handler).OnMyEvent(this);
    }
}
-1

This is similar to Overriding and Inheriting Help . I am pretty sure that you need to use the keyword "virtual" if you want to override the method.

-1
source

All Articles