2017-05-25 95 views
0

我想在C#控制台应用程序(CLI)中编写一个框架,细节并不重要。 我不知道,如何干净地识别命令,并很快。 我试图与开关壳体:带命令行界面的C#框架

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; 
     } 
    } 

我也试过的if-else:

 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]); 
     } 
    } 

我试图命令存储在一个字符串数组,仍然是相同的,长和难看。

还有什么其他方法可以让命令识别更短,更清晰,更容易修改吗? 原谅我的英语。随时纠正我!

+0

尝试谷歌搜索 “C#如何写一个解释” –

+0

看看这篇文章:https://stackoverflow.com/questions/673113/poor-mans-lexer-for-c-sharp –

+0

的NuGet> CommandLineParser –

回答

0

您可以使用Reflection来执行类的方法。

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; 
    } 
} 
+0

NetMage你真棒,我无法写下来,你的帮助有多大。这正是我想要的。 – Oteg

+0

感谢您的NetMage,我的框架开始增长,核心只有3000行代码(Not Ready)。如果你没有帮助,核心应该是4-5千行代码。 – Oteg

+0

虽然我主要是使用Perl编写我的CLI程序(我写前端到Cisco CLI来帮助我的工作),但为我创建CLI一直是一种业余爱好。很高兴帮助你。 – NetMage