我在实现 REPL 接口时做了一些不同的事情。
使用Dictionary<string, Func<string, string>>(实际上,我使用一个封装了实际Func 或Action 的类以及可用于通过生成help 文本来帮助提高应用程序可用性的描述) 使用忽略大小写的字符串比较并将您期望的输入添加到字典中,其中对象是您要执行的函数。
这也变成了自我记录,您也可以自动创建帮助文档!
如果您愿意,我明天可以快速发布一个示例。
-- 在下面添加代码示例的关键部分(来自 Program.cs 文件):
我们将用来捕获 REPL 命令信息的类:
class ReplCommand
{
public string Command { get; set; }
public string HelpText { get; set; }
public Action<string> MethodToCall { get; set; }
public int HelpSortOrder { get; set; }
}
这是我们定义所有有效命令的地方
static void PopulateCommands()
{
// Add your commands here
AddCommand(new ReplCommand
{
Command = "MyCommand", // The command that the user will enter (case insensitive)
HelpText = "This is the help text of my command", // Help text
MethodToCall = MyCommand, // The actual method that we will trigger
HelpSortOrder = 1 // The order in which the command will be displayed in the help
});
// Default Commands
AddCommand(new ReplCommand
{
Command = "help",
HelpText = "Prints usage information",
MethodToCall = PrintHelp,
HelpSortOrder = 100
});
AddCommand(new ReplCommand
{
Command = "quit",
HelpText = "Terminates the console application",
MethodToCall = Quit,
HelpSortOrder = 101
});
}
static void AddCommand(ReplCommand replCommand)
{
// Add the command into the dictionary to be looked up later
_commands.Add(replCommand.Command, replCommand);
}
这是程序的关键部分:
// The dictionary where we will keep a list of all valid commands
static Dictionary<string, ReplCommand> _commands = new Dictionary<string, ReplCommand>(StringComparer.CurrentCultureIgnoreCase);
static void Main(string[] args)
{
// Create Commands
PopulateCommands();
// Run continuously until "quit" is entered
while (true)
{
// Ask the user to enter their command
Console.WriteLine("Please input your command and hit enter");
// Capture the input
string sInput = Console.ReadLine();
// Search the input from within the commands
if (_commands.TryGetValue(sInput, out ReplCommand c))
{
// Found the command. Let's execute it
c.MethodToCall(sInput);
}
else
{
// Command was not found, trigger the help text
PrintHelp(sInput);
}
}
}
上面定义的每条评论的具体实现:
static void MyCommand(string input)
{
Console.WriteLine($"MyCommand has been executed by the input '{input}'");
}
static void PrintHelp(string input)
{
// Unless the input that got us here is 'help', display the (wrong) command that was
// entered that got us here
if (input?.ToLowerInvariant() != "help")
{
// Display the wrong command
Console.WriteLine($"Command '{input}' not recognized. See below for valid commands");
}
// Loop through each command from a list sorted by the HelpSortOrder
foreach (ReplCommand c in _commands.Values.OrderBy(o => o.HelpSortOrder))
{
// Print the command and its associated HelpText
Console.WriteLine($"{c.Command}:\t{c.HelpText}");
}
}
static void Quit(string input)
{
System.Environment.Exit(0);
}
}
}
这是complete Program.cs file的链接。
我已将完整的代码库上传到我的GitHub Repo。