【问题标题】:How do i continuously check for commands in c#?如何在 C# 中不断检查命令?
【发布时间】:2016-07-22 23:49:31
【问题描述】:

我想像这样:

prompt> checkprice
price of foo is 42$
prompt>

运行多个命令。

【问题讨论】:

  • 如果你不知道如何正确表达,想象一下我和其他人理解你的问题有多难......

标签: c# command prompt


【解决方案1】:

也许这个

//this is your price variable
static int price = 42;
//function to check it
static void CheckPrice()
{
    Console.WriteLine("price of foo " + price + "$");
}
static void Main()
{
    bool exit = false;
    do
    {
        //write at begin ">"
        Console.Write(">");
        //wait for user input
        string input = Console.ReadLine();
        // if input is "checkprice"
        if (input == "checkprice") CheckPrice();
        if (input == "exit") exit = true;
    } while (!exit);
}

【讨论】:

    【解决方案2】:

    直到键入特定命令,例如“退出”:

    static void Main(string[] args) {
        var line = System.Console.ReadLine().Trim();
    
        while(line!="exit") {
            myOperationCommand(line);
            line = System.Console.ReadLine().Trim(); // read input again
        }
    
        System.Console.WriteLine("End!\n");
    }
    
    // Do some operation...
    static void myOperationCommand(string line) {
        switch(line) {
            case "checkprice":
                System.Console.WriteLine("price of foo is 42$");
                break;
            default: 
                System.Console.WriteLine("Command not reconized: " + line);
                break;
        }
    }
    

    【讨论】:

      【解决方案3】:

      类似:

      while(true) {
          Console.Write("prompt>");
          var command = Console.ReadLine();
      
          if (command == "command1") doSomething();
          else if (command == "command2") doSomethingElse();
          ...
          else if (command == "quit") break;
      }
      

      【讨论】:

      • 为什么要使用额外的else if?你可以只做while ((command = Console.ReadLine().ToLower()) != "quit") {(这意味着你必须在循环之前声明command)。 --- 另外,.ToLower() 用于不区分大小写的命令。
      • @visualvincent 是的,你可以这样做。我个人不喜欢它,因为 1)你必须在循环之外声明命令(因此在它的实际范围之外) 2)它在某种程度上不是很可读。
      • 1) 点。虽然没多大关系。 2) 我认为这样会变得更具可读性。 ;) -- 虽然 .ToLower() 仍然很好用,这样即使你输入QUITqUiT 等,你的程序仍然会执行你的命令。
      猜你喜欢
      • 1970-01-01
      • 2017-03-10
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多