问题
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 saying that MyEvent
doesn't implement BaseEvent
since Dispatch
is taking an IMyEventHandler
instead of an IEventHandler
. I don't want to let MyEvent.Dispatch
take a IEventHandler
then cast it to a IMyEventHandler
because I would like compile time checks to make sure I'm not doing something stupid like passing in some other type of event handler. I found a possible solution (below) but I'm wondering if there is a nicer way of doing 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
回答1:
I've used your approach before.
It looks pretty solid to me.
回答2:
MyEvent change the abstract method Dispatch's signature. so you got a compile time error.
how about follow code.
public class MyEvent : BaseEvent
{
public override void Dispatch(IEventHandler handler)
{
if(!handler is IMyFirstEventHandler )throw new ArgumentException("message").
((IMyFirstEventHandler )handler).OnMyEvent(this);
}
}
回答3:
This seems pretty similar to Help With Overriding and Inheritance. I'm pretty confident you need to the keyword 'virtual' if you want to override a method.
来源:https://stackoverflow.com/questions/12593082/c-sharp-override-method-with-subclass-parameter