我正在尝试将这个动态双重调度示例移植到 C#。我已经完成了这个示例,但我觉得我已经通过使用反射来创建所需的处理程序并调用适当的方法来简化类DynamicDispatch
中的方法。MessageBase
任何人都可以就如何更改它提供一些建议吗?该示例使用 C++ dynamic_cast 运算符,我不确定 C# 的等价物是什么。我不确定我的解决方案是正确/最好的方法。
注意:我使用的是 3.5,所以我不能使用动态关键字
这是代码:
即时消息
public interface IMessage
{
void Dispatch(IHandler handler);
}
消息库
public abstract class MessageBase : IMessage
{
public abstract void Dispatch(IHandler handler);
// This is my concern, doesnt feel like the right way to do this
protected void DynamicDispatch<MessageType>(IHandler handler, MessageType self)
{
// Get the messages derived type
Type self_type = self.GetType();
// Create actual message specific handler
Type message_handler = typeof(IMessageHandler<>).MakeGenericType(self_type);
// Get the ProcessMessage method
MethodInfo minfo = message_handler.GetMethod("ProcessMessage");
try
{
// Invoke it with the message
minfo.Invoke(handler, new object[] { self });
}
catch (TargetException ex)
{
// Ignore if method doesnt exist
}
}
}
信息
public class Message : MessageBase
{
public override void Dispatch(IHandler handler)
{
DynamicDispatch(handler, this);
}
}
处理程序
public interface IHandler
{
}
消息处理程序
public interface IMessageHandler<MessageType> : IHandler
{
void ProcessMessage(MessageType message);
}
派生消息一
public class DerivedMessageOne : Message
{
public int MessageOneField;
}
派生消息二
public class DerivedMessageTwo : Message
{
public int MessageTwoField;
}
DerivedMessageHandlerOne
public class DerivedMessageHandlerOne : IMessageHandler<DerivedMessageOne>,
IMessageHandler<DerivedMessageTwo>
{
#region IMessageHandler<MessaegType> Members
// ************ handle both messages *************** //
public void ProcessMessage(DerivedMessageOne message)
{
// Received Message one, do soemthing with i
int do_something_with_it = message.MessageOneField;
}
public void ProcessMessage(DerivedMessageTwo message)
{
// Received Message two, do soemthing with i
}
#endregion
}
DerivedMessageHandlerTwo
public class DerivedMessageHandlerTwo : IMessageHandler<DerivedMessageOne>
{
#region IMessageHandler<MessaegType> Members
// ************ handle just MessageOne *************** //
public void ProcessMessage(DerivedMessageOne message)
{
// Received Message one, do soemthing with i
}
#endregion
}
测试用例
IMessage messageOne = new DerivedMessageOne();
IMessage messageTwo = new DerivedMessageTwo();
IHandler handlerOne = new DerivedMessageHandlerOne();
IHandler handlerTwo = new DerivedMessageHandlerTwo();
messageOne.Dispatch(handlerOne);
messageOne.Dispatch(handlerTwo);
messageTwo.Dispatch(handlerOne);
messageTwo.Dispatch(handlerTwo);