- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
哇,多么好的标题...
我正在为一个学习项目开发服务器。我花了很多时间试图弄清楚如何正确地提出这个问题。一开始,我想我什至不知道我想要实现的目标。
我正在使用的服务器有 N 个组件(N >= 0)。
subscribing
提供信息到 message
, 并提供 handler
对于那条消息。我计划使用 handler
上的属性来实现此目的功能。“处理程序”的示例:
[Handles(ExampleMessage)]
private void handleExampleMessage(ExampleMessage message)
{
DoStuff();
}
这是我能想到的最清晰的问题构建方式:
我怎样才能实现类型化“消息代理”系统,就像 ASP.NET MVC 如何为 controller
提供类型化模型一样? action
来自序列化输入。
所以我想实现的是:
Serialized message
-> Strongly typed message
-> message service
-> call handler function with *strongly typed* message as an argument
我想到了一些事情:
我尝试的第一件事就是简单地将消息反序列化为 dynamic
, 但没有 inellisense 和编译时检查对于 dynamic
的简单性来说成本太高了对我来说。
然后我尝试在运行时使用反射创建静态反序列化方法,并使用这些方法的返回值来调用“处理程序”,但它变得太丑和意大利面条了,我不得不放弃它(尽管如果有人有一种优雅的、注重性能的方式,我当然仍然对这个选项持开放态度)
最后我尝试使用 Message
所有消息都继承自的类型,但当我尝试使用 Dictionary<Action<Message>, Message>
时我最终陷入困境调用适当的处理程序
最佳答案
这是可能的,只是有点复杂。您要做的是在组件中搜索具有 Handles
属性的方法,并通过反射调用它们。
假设我们有以下接口(interface):
public interface IComponent
{
}
public interface IMessage
{
};
我们还可以创建 Handles
属性,让我们将方法标记为处理特定消息类型:
[AttributeUsage(AttributeTargets.Method)]
public class HandlesAttribute : Attribute
{
public Type MessageType { get; private set; }
public HandlesAttribute(Type messageType)
{
MessageType = messageType;
}
};
现在我们将创建一个消息代理,它将负责在给定的组件列表中查找所有消息处理方法。我们将使用反射来做到这一点。首先,我们将找到所有具有 Handles
属性的方法,然后我们将检查它们是否具有所需的单个 IMessage
参数:
public class MessageBroker
{
// Encapsulates a target object and a method to call on that object.
// This is essentially our own version of a delegate that doesn't require
// us to explicitly name the type of the arguments the method takes.
private class Handler
{
public IComponent Component;
public MethodInfo Method;
};
private Dictionary<Type, List<Handler>> m_messageHandlers = new Dictionary<Type, List<Handler>>();
public MessageBroker(List<IComponent> components)
{
foreach (var component in components)
{
var componentType = component.GetType();
// Get all private and public methods.
var methods = componentType.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
foreach (var method in methods)
{
// If this method doesn't have the Handles attribute then ignore it.
var handlesAttributes = (HandlesAttribute[])method.GetCustomAttributes(typeof(HandlesAttribute), false);
if (handlesAttributes.Length != 1)
continue;
// The method must have only one argument.
var parameters = method.GetParameters();
if (parameters.Length != 1)
{
Console.WriteLine(string.Format("Method {0} has too many arguments", method.Name));
continue;
}
// That one argument must be derived from IMessage.
if (!typeof(IMessage).IsAssignableFrom(parameters[0].ParameterType))
{
Console.WriteLine(string.Format("Method {0} does not have an IMessage as an argument", method.Name));
continue;
}
// Success, so register!
RegisterHandler(handlesAttributes[0].MessageType, component, method);
}
}
}
// Register methodInfo on component as a handler for messageType messages.
private void RegisterHandler(Type messageType, IComponent component, MethodInfo methodInfo)
{
List<Handler> handlers = null;
if (!m_messageHandlers.TryGetValue(messageType, out handlers))
{
// If there are no handlers attached to this message type, create a new list.
handlers = new List<Handler>();
m_messageHandlers[messageType] = handlers;
}
var handler = new Handler() { Component = component, Method = methodInfo };
handlers.Add(handler);
}
}
上面的构造函数会记录一条警告消息并忽略任何与我们要求的签名不匹配的方法(即从 IMessage 派生的一个参数)。
现在让我们添加一个方法来处理消息。这将使用 Invoke
调用任何已注册的处理程序:
// Passes the given message to all registered handlers that are capable of handling this message.
public void HandleMessage(IMessage message)
{
List<Handler> handlers = null;
var messageType = message.GetType();
if (m_messageHandlers.TryGetValue(messageType, out handlers))
{
foreach (var handler in handlers)
{
var target = handler.Component;
var methodInfo = handler.Method;
// Invoke the method directly and pass in the method object.
// Note that this assumes that the target method takes only one parameter of type IMessage.
methodInfo.Invoke(target, new object[] { message });
}
}
else
{
Console.WriteLine(string.Format("No handler found for message of type {0}", messageType.FullName));
}
}
};
现在为了测试它,我们将使用这些示例消息和组件。我还添加了一些配置错误的测试方法(即错误的参数):
public class ExampleMessageA : IMessage
{
};
public class ExampleMessageB : IMessage
{
};
public class ExampleComponent : IComponent
{
[Handles(typeof(ExampleMessageA))]
public void HandleMessageA(ExampleMessageA message)
{
Console.WriteLine(string.Format("Handling message of type ExampleMessageA: {0}", message.GetType().FullName));
}
[Handles(typeof(ExampleMessageB))]
public void HandleMessageB(ExampleMessageB message)
{
Console.WriteLine(string.Format("Handling message of type ExampleMessageB: {0}", message.GetType().FullName));
}
[Handles(typeof(ExampleMessageA))]
public void HandleMessageA_WrongType(object foo)
{
Console.WriteLine(string.Format("HandleMessageA_WrongType: {0}", foo.GetType().FullName));
}
[Handles(typeof(ExampleMessageA))]
public void HandleMessageA_MultipleArgs(object foo, object bar)
{
Console.WriteLine(string.Format("HandleMessageA_WrongType: {0}", foo.GetType().FullName));
}
}
最后把它们放在一起:
var components = new List<IComponent>() { new ExampleComponent() };
var messageBroker = new MessageBroker(components);
// A message has been received and deserialised into the correct type.
// For prototyping here we will just instantiate it.
var messageA = new ExampleMessageA();
messageBroker.HandleMessage(messageA);
var messageB = new ExampleMessageB();
messageBroker.HandleMessage(messageB);
您应该得到以下输出:
Method HandleMessageA_WrongType does not have an IMessage as an argument
Method HandleMessageA_MultipleArgs has too many arguments
Handling message of type ExampleMessageA: Program+ExampleMessageA
Handling message of type ExampleMessageB: Program+ExampleMessageB
您可以玩的完整 fiddle 是 here .
要提高方法调用性能,您可以使用提到的技术重写 MethodInfo.Invoke
here .
关于c# - 如何将消息反序列化为强类型对象,然后为该消息动态调用运行时分配的处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50616158/
我一直在读到,如果一个集合“被释放”,它也会释放它的所有对象。另一方面,我还读到,一旦集合被释放,集合就会释放它的对象。 但最后一件事可能并不总是发生,正如苹果所说。系统决定是否取消分配。在大多数情况
我有一个客户端-服务器应用程序,它使用 WCF 进行通信,并使用 NetDataContractSerializer 序列化对象图。 由于服务器和客户端之间传输了大量数据,因此我尝试通过微调数据成员的
我需要有关 JMS 队列和消息处理的帮助。 我有一个场景,需要针对特定属性组同步处理消息,但可以在不同属性组之间同时处理消息。 我了解了特定于每个属性的消息组和队列的一些知识。我的想法是,我想针对
我最近开始使用 C++,并且有一种强烈的冲动 #define print(msg) std::cout void print(T const& msg) { std::cout void
我已经为使用 JGroups 编写了简单的测试。有两个像这样的简单应用程序 import org.jgroups.*; import org.jgroups.conf.ConfiguratorFact
这个问题在这里已经有了答案: Firebase messaging is not supported in your browser how to solve this? (3 个回答) 7 个月前关
在我的 C# 控制台应用程序中,我正在尝试更新 CRM 2016 中的帐户。IsFaulted 不断返回 true。当我向下钻取时它返回的错误消息如下: EntityState must be set
我正在尝试通过 tcp 将以下 json 写入 graylog 服务器: {"facility":"GELF","file":"","full_message":"Test Message Tcp",
我正在使用 Django 的消息框架来指示成功的操作和失败的操作。 如何排除帐户登录和注销消息?目前,登录后登陆页面显示 已成功登录为“用户名”。我不希望显示此消息,但应显示所有其他成功消息。我的尝试
我通过编写禁用qDebug()消息 CONFIG(release, debug|release):DEFINES += QT_NO_DEBUG_OUTPUT 在.pro文件中。这很好。我想知道是否可以
我正在使用 ThrottleRequest 来限制登录尝试。 在 Kendler.php 我有 'throttle' => \Illuminate\Routing\Middleware\Throttl
我有一个脚本,它通过die引发异常。捕获异常时,我想输出不附加位置信息的消息。 该脚本: #! /usr/bin/perl -w use strict; eval { die "My erro
允许的消息类型有哪些(字符串、字节、整数等)? 消息的最大大小是多少? 队列和交换器的最大数量是多少? 最佳答案 理论上任何东西都可以作为消息存储/发送。实际上您不想在队列上存储任何内容。如果队列大部
基本上,我正在尝试创建一个简单的 GUI 来与 Robocopy 一起使用。我正在使用进程打开 Robocopy 并将输出重定向到文本框,如下所示: With MyProcess.StartI
我想将进入 MQ 队列的消息记录到数据库/文件或其他日志队列,并且我无法修改现有代码。是否有任何方法可以实现某种类似于 HTTP 嗅探器的消息记录实用程序?或者也许 MQ 有一些内置的功能来记录消息?
我得到了一个带有 single_selection 数据表和一个命令按钮的页面。命令按钮调用一个 bean 方法来验证是否进行了选择。如果不是,它应该显示一条消息警告用户。如果进行了选择,它将导航到另
我知道 MSVC 可以通过 pragma 消息做到这一点 -> http://support.microsoft.com/kb/155196 gcc 是否有办法打印用户创建的警告或消息? (我找不到谷
当存在大量节点或二进制数据时, native Erlang 消息能否提供合理的性能? 情况 1:有一个大约 50-200 台机器的动态池(erlang 节点)。它在不断变化,每 10 分钟大约添加或删
我想知道如何在用户登录后显示“欢迎用户,您已登录”的问候消息,并且该消息应在 5 秒内消失。 该消息将在用户成功登录后显示一次,但在同一 session 期间连续访问主页时不会再次显示。因为我在 ho
如果我仅使用Welcome消息,我的代码可以正常工作,但是当打印p->client_name指针时,消息不居中。 所以我的问题是如何将消息和客户端名称居中,就像它是一条消息一样。为什么它目前仅将消
我是一名优秀的程序员,十分优秀!