我正在使用一些 .NET 框架,它允许注册 Action<IMessage>
的事件处理程序类型。
IMessage 是接收到的所有消息都在实现的接口(interface)。
我希望能够(以某种方式)注册知道收到的消息的具体类型的处理程序,以便更彻底地记录它。
与此类似的东西:
manager.Register(SpecialHandler);
public void SpecialHandler(SpecialMessage msg)
{
// log.
}
- SpecialMessage 是一种实现 IMessage 的类型。
这是不可能的,有没有简单的方法可以做到这一点?
最佳答案
// improved version of Travis Gockel's approach
void Register<T>(Action<T> action, bool invokeOnTypeMismatch = false)
where T : IMessage
{
Action<IMessage> wrapped = (msg) =>
{
if (msg is T)
{
action((T)msg);
}
else if (invokeOnTypeMismatch)
{
action(default(T));
}
};
// private Action<IMessage> method = delegate{};
method += wrapped;
}
关于c# - 通用事件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8773886/