我想为简单的机器人创建一个控制面板。我可以使用一些命令
我开始创建它(此处缺少一些错误处理)
private static void Main(string[] args)
{
string input = Console.ReadLine();
string[] inputSegments = input.Split();
string commandSegment = inputSegments[0];
switch (commandSegment)
{
case "MOV":
string movementDirectionSegment = inputSegments[1];
string movementRangeSegment = inputSegments[2];
int unitsToMove = Convert.ToInt32(movementRangeSegment);
if (movementDirectionSegment == "F")
{
Move(true, unitsToMove);
}
else if (movementDirectionSegment == "B")
{
Move(false, unitsToMove);
}
else
{
// wrong parameters
}
break;
case "TRN":
string rotationSegment = inputSegments[1];
if (rotationSegment == "L")
{
Rotate(false);
}
else if (rotationSegment == "R")
{
Rotate(true);
}
else
{
// wrong parameters
}
break;
case "RCK":
Collect();
break;
case "RLS":
Drop();
break;
case "ANL":
Analyse();
break;
case "PIC":
TakePicture();
break;
case "LOG":
ShowCommandHistory();
break;
case "HLP":
ShowCommands();
break;
default:
// Command not found
break;
}
Console.ReadLine();
}
我考虑过用命令字典替换开关。我的第一次尝试是
private static readonly Dictionary<string, Action> commands = new Dictionary<string, Action>()
{
{ "MOV", Move },
{ "TRN", Rotate },
{ "RCK", Collect },
{ "RLS", Drop },
{ "ANL", Analyse },
{ "PIC", TakePicture },
{ "LOG", ShowCommandHistory },
{ "HLP", ShowCommands },
};
但是您知道Move
和Rotate
带有一些参数
private static void Move(bool moveForward, int units)
{
// ...
}
private static void Rotate(bool rotateRight)
{
// ...
}
和诸如F
之类的参数需要进行验证。有效的KeyValuePair<string, Action>
将是
{ "MOV {x} {y}", Move(x, y) } // x can be F or B, y is an integer
我可以使用某些东西吗?使用开关很好,但我认为可能会有更好的解决方案。
答案 0 :(得分:4)
在每个命令方法中移动参数内部的处理。然后您的字典将如下所示:
private static readonly Dictionary<string, Action<string[]>> commands = …;
最终将更好地封装命令的逻辑。