切换案例或if [英] switch case or by if
问题描述
我有一个字符数组数组。
char [] ReadBuffers = new char [10];
i将获得commads但序列号port为字符串。
string HDR_CMD =0x00010001
string DBCMD =0x00020002
string DBBdta_CMD =0x00030003
string ADDR_TBL_CMD =0x00040004
string RESEND_CMD =0x00050005
i want放置条件。
i将通过串口获取命令,只有该命令应通过char缓冲区读取。
然后通过串口写入。
我们怎么办呢。
请帮帮我。
i have an char array array.
char[] ReadBuffers = new char[10];
i will get commads though serial port as a string.
string HDR_CMD = "0x00010001"
string DBCMD = "0x00020002"
string DBBdta_CMD = "0x00030003"
string ADDR_TBL_CMD = "0x00040004"
string RESEND_CMD = "0x00050005"
i want to put conditions.
i will get command through serial port only that command should read through char buffer.
and then write through serial port.
how can we do this.
please help me.
推荐答案
您可以使用任何一种非控制流结构方法。这取决于您的解决方案。例如,当命令出现时你将要做什么,将添加命令等等。我在下面提出的建议可能是不必要的 - 只是过度工程。
这是我头脑中的问题,但它会给你一个想法。您不必使用ICommand(它可以包括Action< t>或Func< t>)。
You can use either, or a non-control flow structure approach. It depends on your solution. For example, what are you going to do when the command comes, will commands ever be added, etc. What I am proposing below may be unnecessary -- just over-engineering.
This is something off the top of my head, but it'll give you an idea. You don't have to use an ICommand (it can be anything including an Action<t> or Func<t>).
static class CommandRepository {
Dictionary<string, ICommand> commands;
static CommandRepository() {
commands = new Dictionary<string, ICommand>(5);
commands.Add("0x00010001", new ...);
commands.Add("0x00020002", new ...);
...
}
public static ICommand GetCommand(string cmdStr) {
if (commands.ContainsKey(cmdStr))
return commands[cmdStr];
else
return null;
}
}
然后你会在你的代码中使用这个类。
You would then use this class in your code.
void ExecuteCommand(string cmdStr) {
var cmd = CommandRepository.GetCommand(cmdStr);
if (cmd != null)
cmd.Execute();
else
throw new Exception(); // do something when invalid cmdStr
}
如果你计划大量或动态地添加命令,你可以更进一步。通过使用像Unity这样的IoC容器。您可以对此进行自己的研究,但是您可以通过配置文件注册具有不同注册名称的多个命令,并使用它来解析对象而不是使用字典。
You can take this further if you plan on adding commands a lot or perhaps dynamically. By using an IoC container like Unity. You can do your own research on that, but you could through a configuration file register multiple commands with different registration names and use that to resolve the objects instead of using a Dictionary.
这篇关于切换案例或if的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!