gpt4 book ai didi

.net - 设计这个循环的更好方法?

转载 作者:行者123 更新时间:2023-12-02 06:45:06 26 4
gpt4 key购买 nike

我正在为我自己的自定义汇编风格构建一个简单的汇编编译器,我有类似这样的代码作为进行编译的实际代码:

    foreach (KeyValuePair<short, string> kvp in newCommandSet)
{
string fullCommandString = kvp.Value;

string instruction = fullCommandString.Split(new char[] { Convert.ToChar(" ") })[0];
string[] parameters = fullCommandString.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
// this is to remove the instruction part from the first parameter. Gonna have to ensure a well formed command at some point...
parameters[0] = parameters[0].Substring(instruction.Length + 1);
Command currentCommand = new Command();
switch (instruction)
{
case "load":
short value = Convert.ToInt16(instruction[0]);
byte register = Convert.ToByte(parameters[1]);
currentCommand = CommandFactory.CreateLoadCommand(register, value);
break;
case "input":
byte channel = Convert.ToByte(parameters[0]);
register = Convert.ToByte(parameters[1]);
currentCommand = CommandFactory.CreateInputCommand(register, channel);
break;
case "output":
channel = Convert.ToByte(parameters[0]);
register = Convert.ToByte(parameters[1]);
currentCommand = CommandFactory.CreateInputCommand(register, channel);
break;
...
}
...
}

感觉我在这里打破了大约六条设计规则(重用变量和期望格式正确的输入是我唯一能发现的,但我敢打赌还有更多),但不知道如何更好地构建它.想法?

最佳答案

考虑将解释参数的逻辑推送到 CommandFactory 中。 switch 语句如下所示:

switch(instruction)
{
case "load":
currentCommand = CommandFactory.CreateLoadCommand(parameters);
break;
case "input":
currentCommand = CommandFactory.CreateInputCommand(parameters);
break;
case "output":
currentCommand = CommandFactory.CreateOutputCommand(parameters);
break;
}

关于.net - 设计这个循环的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1530386/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com