Today I was experimenting with a borrowing a Delphi concept of dynamic method dispatching through a message id. I implemented the concept in C# and thought I'd share. I wanted to be able to do this in C# (Delphi code follows):
procedure WMMouseMove(var Message: TWMMouseMove); message WM_MOUSEMOVE;
The above line of Delphi code defines a method which is dispatched through of data passed as a parameter (an event id). In this case in response to the WM_MOUSEMOVE constant. It's sort of an event oriented form of polymorphism, where any object cam listen to any event and respond or simply pass the event on to a default handler.
I came up with a similar working solution in C#. Here is what the the code looks like (feedback appreciated):
[Message(Messages.MouseMove)]
private void CanBeAnyName(Type type, Message message)
{
BaseHandler(type, message); // invoke next base methods matching the same event id: Messages.MouseMove
// place your specific message handling code here
}
Invocation:
instance.Dispatch(new MouseMoveMessage(X, Y));
Where "MouseMoveMessage" is a message or message derived class, and instance is a "DispatchObject".
Mind you, I am doing a few things here.
1) Dispatch calls only the most derived method with the matching message id.
2) The name of the method "CanBeAnyName" is irrelevent. The message id is used to find the method dynamically.
3) Inherited message handlers can be invoked through the protected "BaseHandler" method.
4) If no methods with a matching id are found, a virtual "DefaultHandler" method is called.
Source code listing: http://codebot.org/dispatch.txt