带有命令行界面的C#框架
我想在C#控制台应用程序(CLI)中编写一个框架,细节并不重要。 我不知道,如何快速清晰地识别命令。 我试过使用开关盒:带有命令行界面的C#框架,c#,command,command-line-interface,C#,Command,Command Line Interface,我想在C#控制台应用程序(CLI)中编写一个框架,细节并不重要。 我不知道,如何快速清晰地识别命令。 我试过使用开关盒: public static void command_recognizing(string command) // random example { string[] tmp_array = command.Split(' '); switch(tmp_array[0]) { case("
public static void command_recognizing(string command) // random example
{
string[] tmp_array = command.Split(' ');
switch(tmp_array[0])
{
case("help"):
method_library.help(); // no need argument
break;
case("time"):
method_library.time(); // no need argument
break;
case("shutdown"):
method_library.shutdown(tmp_array); // need argument
break;
default:
Console.WriteLine("Error! {0} is not a known command!",tmp_array[0]);
break;
}
}
我还尝试了以下方法:
public static void command_recognizing(string command) // random example
{
string[] tmp_array = command.Split(' ');
if(command.Contains("help"))
{
method_library.help(); // no need argument
}
else if(command.Contains("time"))
{
method_library.time(); // no need argument
}
else if(command.Contains("shutdown"))
{
method_library.shutdown(tmp_array); // need argument
}
else
{
Console.WriteLine("Error! {0} is not a known command!",tmp_array[0]);
}
}
我试图将命令存储在一个字符串数组中,仍然是一样的,长而难看
还有其他方法可以使命令更短、更清晰、更易于修改吗?
为我的英语付出代价。请随意纠正我 您可以使用反射来执行类的方法
void Main() {
var cmd = new Commands();
while (!cmd.Exitting) {
var cmdline = Console.ReadLine();
var cmdargs = Regex.Split(cmdline.Trim(), @"\s+");
if (!cmd.TryInvokeMember(cmdargs[0], cmdargs.Skip(1).ToArray()))
Console.WriteLine($"Unknown command: {cmdargs[0]}");
}
}
// Define other methods and classes here
public class Commands {
public bool Exitting { get; private set; }
public Commands() {
Exitting = false;
}
public void exit() {
Exitting = true;
}
public int sum(object[] args) {
return args.Select(s => Convert.ToInt32(s)).Sum();
}
public bool TryInvokeMember(string methodName, object[] args) {
var method = typeof(Commands).GetMethod(methodName.ToLower());
if (method != null) {
object res;
if (method.GetParameters().Length > 0)
res = method.Invoke(this, new object[] { args });
else
res = method.Invoke(this, new object[0]);
if (method.ReturnType != typeof(void))
Console.WriteLine(res.ToString());
return true;
}
else
return false;
}
}
试试谷歌搜索“c#如何编写解释器”看看这篇文章:Nuget>CommandLineParserPeter Bons,我花了一周时间尝试编写一个普通的解析器。失败后,我花了3天时间搜索一个,当然什么也没有。大卫·坦西:这没用。Nuget也不起作用。非常感谢NetMage。NetMage你太棒了,我无法写下,你的帮助有多大。这正是我想要的。多亏了你NetMage,我的框架开始成长,核心只有3000行代码(还没有准备好)。如果你不帮忙,核心应该是4000-5000行代码。虽然我主要用Perl编写CLI程序(我为Cisco CLI编写前端以帮助我的工作),但为我创建CLI一直是我的爱好。很高兴它帮助了你。