【发布时间】:2012-05-13 05:56:24
【问题描述】:
我正在制作text adventure in C#,有人建议我使用dispatch table 而不是switch 语句。
下面是switch语句代码:
#region Public Methods
public static void Do(string aString)
{
if(aString == "")
return;
string verb = "";
string noun = "";
if (aString.IndexOf(" ") > 0)
{
string[] temp = aString.Split(new char[] {' '}, 2);
verb = temp[0].ToLower();
noun = temp[1].ToLower();
}
else
{
verb = aString.ToLower();
}
switch(Program.GameState)
{
case Program.GameStates.Playing:
if (IsValidInput(Commands, verb, true))
{
switch(verb) //this is the switch statement
{
case "help":
case "?":
WriteCommands();
break;
case "exit":
case "quit":
Program.GameState = Program.GameStates.Quit;
break;
case "move":
case "go":
MoveTo(noun);
break;
case "examine":
Examine(noun);
break;
case "take":
case "pickup":
Pickup(noun);
break;
case "drop":
case "place":
Place(noun);
break;
case "use":
Use(noun);
break;
case "items":
case "inventory":
case "inv":
DisplayInventory();
break;
case "attack":
//attack command
break;
}
}
break;
case Program.GameStates.Battle:
if(IsValidInput(BattleCommands, verb, true))
{
switch(verb) //this is the other switch statement
{
case "attack":
//attack command
break;
case "flee":
case "escape":
//flee command
break;
case "use":
//use command
break;
case "items":
case "inventory":
case "inv":
//items command
break;
}
}
break;
}
}
#endregion
如何重构它以使用调度表?
【问题讨论】:
-
您应该看看this question,其中一个答案显示了一个看起来非常正确的 C# 示例,恕我直言。
-
在我担心这个之前,我会专注于编写更小更模块化的函数 ;-)
-
@psycho 这完美地回答了我的问题。您应该将此作为答案发布,以便我接受。
-
@pst 你能给我举个例子说明要解决什么吗?
-
@ryansworld10 我可能会将每个游戏状态逻辑都放在它自己的函数中,这样分支(开关或调度或其他)就不会嵌套。
标签: c# adventure dispatch-table