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
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.
Because a and b and c , so it's name is C. C came out of Ken Thompson's Unix project at AT&T. He originally wrote Unix in assembly language. He wrote a language in assembly called B that ran on Unix, and was a subset of an existing language called BCPL.
I've used your approach before.
It looks pretty solid to me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With