我建立了裝配自己的自定義的味道簡單的組裝編譯器,我有這樣的事情作爲實際的代碼,不會編譯:更好的方法來設計這個循環?
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函數的重載?我喜歡.... – RCIX 2009-10-07 10:02:40